我有2个实体:Account和AccountRole。
Account
AccountRole
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
只需更换
entityManager.persist(account);
与:
entityManager.merge(account);
并允许合并级联:
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER) public AccountRole getAccountRole() { return accountRole; }
因为合并会这样做:
如果您的实体是新实体,则与persist()相同。但是,如果您的实体已经存在,它将对其进行更新。