Is there a way to pass detached object to JPA persist? (detached entity passed to persist)

前端 未结 3 2033
梦如初夏
梦如初夏 2020-12-28 21:45

I have 2 entities : Account and AccountRole.

public class Account {
   private AccountRole accountRole;

   @ManyToOne(cascade = Ca         


        
3条回答
  •  死守一世寂寞
    2020-12-28 22:22

    Just replace the

    entityManager.persist(account);
    

    with:

    entityManager.merge(account);
    

    And allow merge cascading:

    @ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER)
    public AccountRole getAccountRole() {
        return accountRole;
    }
    

    Because merge does this:

    If your entity is new, it's the same as a persist(). But if your entity already exists, it will update it.

提交回复
热议问题