I'm a little confused with bidirectional OneToOne
relationship, which may not be optional on both ends. I'm using JPA2 with Hibernate:
@Entity
@Table(name = "city")
public class City {
@Id
@GeneratedValue
@Column
public Long _UID;
@OneToOne(mappedBy="city", optional=false, orphanRemoval = true, cascade=CascadeType.ALL)
public Mayor mayor;
}
@Entity
@Table(name = "mayor")
public class Mayor {
@Id
@GeneratedValue
@Column
public Long _UID;
@OneToOne(optional=false, cascade=CascadeType.ALL)
public City city;
}
And if I try this transaction:
Mayor m = new Mayor("Ed", "Lee");
City c = new City("San Francisco", 100000);
m.setCity(c);
c.setMayor(m);
EntityTransaction et = this.getEm().get().getTransaction();
et.begin();
this.getEm().get().persist(c);
this.getEm().get().flush();
et.commit();
I get following exception:
javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: test.persistence.entity.Mayor.city
If I inspect City
instance before it get persisted, it has a Mayor
instance on a right place and this Mayor
instance has a relationship set back to the City
instance.
With optional=false
only on the City side all is ok.