orphanRemoval =真双向OneToOne

时间:2013-03-01 22:26:51

标签: java hibernate jpa

我对双向OneToOne关系以及删除孤儿感到困惑。这些是我的实体:

@Entity
@Table(name = "city")
public class City {

    @Id
    @GeneratedValue
    @Column
    public Long _UID;

    @OneToOne(mappedBy="city", orphanRemoval = true, cascade=CascadeType.ALL)
    public Mayor mayor;
}

@Entity
@Table(name = "mayor")
public class Mayor {

    @Id
    @GeneratedValue
    @Column
    public Long _UID;

    @OneToOne(optional=false)
    public City city;
}

如果我尝试这个交易:

City c = em.find(City.class, (long) 1);
AssertNotNull(c.getMayor());//gives true
Mayor m = new Mayor("Ed", "Lee");
c.setMayor(m);
m.setCity(c);
em.flush(); //This creates new Mayor and adds it to City, but don't delete an old one.

如果我将mayor设置为null并在设置new之前刷新,则它可以工作:

City c = em.find(City.class, (long) 1);
AssertNotNull(c.setMayor());//gives true
c.setMayor(null);
em.flush();
Mayor m = new Mayor("Ed", "Lee");
c.setMayor(m);
m.setCity(c);
em.flush(); //This creates new Mayor and adds it to City, but don't deletes an old one.

我使用Hibernate 4作为JPA2实现。

2 个答案:

答案 0 :(得分:1)

这是Hibernate中的一个已知问题(实际上是在JPA规范中)。

有关问题背景和可能的解决方法的更多信息,请参阅this bug report。您可以投票支持同一问题another ticket,因为前者已经关闭。

答案 1 :(得分:0)

  1. 请删除(optional=false)
  2. 您必须在em.clear()
  3. 之后em.flush()进行操作