私は2つのエンティティ:Account
とAccountRole
を持っています。分離されたオブジェクトをJPAに引き渡す方法はありますか? (分離されたエンティティが継承に渡されます)
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: detached entity passed to persistそして、私は理解し、私は私のセッターでやっているものをするように、私は、両方の方向からのエンティティの値を設定する必要があります。
まだエラーが発生しています。
org.hibernate.PersistentObjectException: detached entity passed to persist: foo.bar.pojo.AccountRole
また、 'persist()'はあなたがマネージエンティティを渡したオブジェクトを作成しますが、mergeは渡されたオブジェクトのマネージドコピーを返します。したがって、マージ後にマネージドエンティティが必要な場合は、 'account = entityManager.merge(account)'を実行する必要があります。また、[こちら]を見てください(http://stackoverflow.com/a/1070629/1260908) – rumman0786