How to simply add an object to a collection from hibernate from a client

I am trying to add an object to a collection in my client view and store it on the server using the hibernate / jpa mechanism.

Here's the problem: Take a Group object, which may contain Account objects.

In my client view (gwt), I create a new group (so the identifier is null), and I add some accounts to this group (where ids exist). BUT these accounts are initialized on the client with their identifier and pseudo only through the proposal field (because I do not want to load the password and other things in my client view)

When my group returns to the server, I try to save it using my dao, and I have this error: not-null refers to a null value or a transition value

Here is my association in the Group object:

@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH })
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public Set<Account> getAccounts()
{
    return accounts;
}

therefore, saving should be done automatically. But I think the problem is that I am using partial account objects with an existing identifier.

My question is: how can I add a simple association (just add an entry to the manyToMany table) without loading all the objects that I want to add (because I do not need it, I just want to add a connection between two id)

EDIT: more information on an example: I have a group whose properties are ID: "G1" name: "group1"

I have an account whose properties ID: "A1" Pseudo: "Jerome" password: "pass1" Status: "enabled" birthday: "xxxx" ...

( gwt) group1 Account, ( ). Account "Jerome" "A1" .

, . , , : groupDAO.update(myGroup1)

Account Group , .

, ? :

List newList = new ArrayList();
for (Account acc : myGroup1.getAccounts())
{
    Account accLoaded = accountDAO.findById(acc.getId());
    newList.add(accLoaded);
}

myGroup1.setAccounts(newList);
groupDAO.save(myGroup1);

+3
1

:

id Account

:

, , id

. ,

public class Account {

    private Integer id;

    private Integer accountNumber;

    @Id
    public Integer getId() {
        return this.id;
    }

    @Column(nullable=false)
    public Integer getAccountNumber() {
        return this.accountNumber;
    }

}

,

Group group = new Group();

// Notice as shown bellow accountNumber is null
Account account = new Account();
account.setId(1);

group.addAccount(account);

entityManager.persist(group);

, - CascadeType.PERSIST

Account AccountNumber NULL. ,

-

// If you do not want to hit the database
// Because you do not need a fully initialized Account
// Just use getReference method
Account account = entityManager.getReference(Account.class, new Integer(accountId));

, - .

,

+4

Source: https://habr.com/ru/post/1727465/


All Articles