问题描述
我有两个实体:帐户
和 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(){
返回帐户;
$ b 问题出在我从数据库中取出accountRole并试图保存我的帐户
。 此时,我刚刚创建了我的账户和角色,并已存在于db中。
AccountRole role = accountService .getRoleFromDatabase(AccountRoles.ROLE_USER);
account.setAccountRole(role);
//根据建议设置两种方式
public void setAccountRole(AccountRole accountRole){
accountRole.addAccount(this);
this.accountRole = accountRole;
}
entityManager.persist(account); //终于在我的DAO
我读了这个: 我的理解是,我必须设置两个实体的值方向,这样我在我的setter中做的事。
仍然出错。
org.hibernate.PersistentObjectException:传递给persist的分离实体:foo.bar.pojo.AccountRole
只需将
entityManager.persist(account)替换为 ;
附带:
entityManager.merge(帐户);
并允许合并级联:
<$ p $
public AccountRole getAccountRole(){
return accountRole; $ {code> @ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE},fetch = FetchType.EAGER)
$ / code>
因为合并是这样做的:
I have 2 entities : Account
and 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;
}
Problem comes when I take the accountRole from database and try to persist my Account
. At this point I just created my account and role already exists in 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
I read this : JPA/Hibernate: detached entity passed to persist And what I understood, I must set the entities values from both direction, so that what I am doing in my setter.
Still getting error.
org.hibernate.PersistentObjectException: detached entity passed to persist: foo.bar.pojo.AccountRole
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:
这篇关于有没有办法将分离的对象传递给JPA? (传递给持久化的分离实体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!