我对双向 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 实现。