小编典典

有没有办法将分离的对象传递给JPA持久化?(独立实体已传递以保留)

hibernate

我有2个实体:AccountAccountRole

public class Account {
   private AccountRole accountRole;

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

public class AccountRole {
    private Collection<Account> accounts = new ArrayList<Account>();

    @OneToMany(mappedBy = "accountRole", fetch = FetchType.EAGER)
    public Collection<Account> getAccounts() {
         return accounts;
    }

问题出在我从数据库中获取accountRole并尝试保留我的Account至此,我刚刚创建了我的帐户,并且角色已经存在于db中。

AccountRole role = accountService.getRoleFromDatabase(AccountRoles.ROLE_USER);
account.setAccountRole(role);

//setting both ways, as suggested
public void setAccountRole(AccountRole accountRole) {
    accountRole.addAccount(this);
    this.accountRole = accountRole;
}

entityManager.persist(account); // finally in my DAO

仍然出现错误。

 org.hibernate.PersistentObjectException: detached entity passed to persist: foo.bar.pojo.AccountRole

阅读 266

收藏
2020-06-20

共1个答案

小编典典

只需更换

entityManager.persist(account);

与:

entityManager.merge(account);

并允许合并级联:

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

因为合并会这样做:

如果您的实体是新实体,则与persist()相同。但是,如果您的实体已经存在,它将对其进行更新。

2020-06-20