我对双向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.


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

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实现。

最佳答案

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

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

09-25 21:05