I'm a little confused with bidirectional OneToOne relationship, and removing of orphans. These are my entities:
Code:
@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;
}
And if I try this transaction:
Code:
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.
If I set mayor to null and flush before set new one, it works:
Code:
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.
The same pattern with @OneToMany works like a charm.
I use Hibernate 4.1.9.