我有 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: detached entity pass to persist 而我的理解是,我必须从两个方向设置实体值,这样我在我的设置器中所做的事情。
仍然出现错误。
org.hibernate.PersistentObjectException: detached entity passed to persist: foo.bar.pojo.AccountRole