jpa级联坚持多对一

时间:2012-05-16 12:59:34

标签: java hibernate jpa persistence

我有两个JPA实体(Account和Person),具有双向关系:

@Entity
@Table(name = "ACCOUNTS")
@DataCache(enabled = false)
public class Account
{
    ....
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "ID_OWNER", nullable = false)
    private Person owner;
    ...
}

@Entity
@Table(name = "OWNERS")
@DataCache(enabled = false)
public class Person {
    ...
    @Column(name = "HAS_ACCOUNTS", nullable = false, columnDefinition = "CHAR(1)")
    private char hasAccounts;

    @OneToMany(mappedBy = "owner")
    private Set<Accpunt> comments = new LinkedHashSet<Account>(3);
    ...
}

当我坚持一个人时,我不想坚持所有帐户,但是当我坚持一个帐户时,我想更新人员属性hasAccounts,所以我还需要更新该人。

我做了以下步骤:

  • 创建人
  • 坚持这个人
  • 创建帐户
  • 修改所有者(之前创建的
  • 保留帐户(我希望它自动合并人员)
Person p = new Person();
em.persist(p);
Account a = new Account();
a.setOwner(p);
p.setHasAccounts('Y');
em.persist(a);

我得到了这个例外:

   javax.ejb.EJBTransactionRolledbackException: org.hibernate.PersistentObjectException: detached entity passed to persist: Person

(我使用带有Hibernate的JPA 1.0)。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

Person p = new Person();
Account a = new Account();

p.getComments().add(a);
p.setHasAccounts('Y');

em.persist(p);