[英]Is there a way to pass detached object to JPA persist? (detached entity passed to persist)
我有2个实体: 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
我读到这个: JPA / Hibernate:传递给persist的分离实体 我理解的是,我必须从两个方向设置实体值,以便我在我的setter中做什么。
仍然有错误。
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()相同。 但是如果您的实体已经存在,它将更新它。
看起来您在处理期间离开了事务,因此accountRole
被分离,或者由于其他原因已经分离。
在调用entityManager.merge(accountRole)
之前调用entityManager.merge(accountRole)
entityManager.persist(account)
应该修复它。
编辑:不幸的是,如果您无法确定数据库中是否已存在accountRole
,则必须通过查询来检查它。 如果存在 - 合并,如果不存在 - 继续。 这确实很麻烦,但我还没有看到更好的解决方法。
EDIT2:您传递给实体merge
方法将保持断开状态-托管实体将被返回的merge
,所以你需要首先合并,然后在基准设置account
到的返回值merge
。
你不能传递一个数据库实体来坚持,没有办法。 但你不需要。
您希望独立于AccountRole
(已保留)持久保存Account
。 为了实现这一点,只需从@ManyToOne
中的@ManyToOne
中删除级联 (在本例中为Account
):
public class Account {
private AccountRole accountRole;
@ManyToOne // no cascading here!
public AccountRole getAccountRole() {
return accountRole;
}
请参阅我的解释,原因如下: https : //stackoverflow.com/a/54271569/522578
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.