1. The difference between the persist and merge methods of EntityManaget

1. The difference between persist and merge :

Persist: add

Merge: There are two cases, when the object has an id, it is modified; when the object does not have an id, it is added.

See an example:

 1  1 public class Account {
 2  2    private AccountRole accountRole;
 3  3    @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
 4  4    public AccountRole getAccountRole() {
 5  5       return accountRole;
 6  6    }
 7  7 
 8  8 //添加account的代码段
 9  9 AccountRole role = accountService.getRoleFromDatabase(AccountRoles.ROLE_USER);
10 10 account.setAccountRole(role);
11 11 entityManager.persist(account);//entityManager.merge(account)

 

Problem description: The role is queried from the database. In this case, the persist method is used to save the account object, and the persist will also save the role. At this time, because the role record already exists in the database, so

At this time, calling persist(account); will report an exception.

Solution:

1. You can cancel saving the associated object when the persist method is called, that is, cancel cascade = CascadeType.PERSIST

2. The merge method can be used instead of persist .

So it can be seen from this that persist is directly saved, and merge is to determine whether to save or modify according to whether the id exists (if the id exists, modify it; if the id does not exist, add it),

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325225833&siteId=291194637