Tuesday, 7 February 2012

Backref Hibernate exception


One of the possible reasons for

org.hibernate.PropertyValueException: not-null property references a null or transient value: com.server.X._YBackref

is cascading same data multiple time.

For Example you have have two classes

Class Person {
List<Car> carsOwned;
Car preferredCar;
….
}

Class Car {
….
}

And the mapping

<bag name="carsOwned" table="person_cars" access="property" cascade="all,delete-orphan">
   <key column="person_id" not-null="true" update="false" />
   <one-to-many class="Car" />     
</bag>

<many-to-one name="preferredCar" class="Car" column="preferred_car_id" not-null="false" unique="true" cascade="all,delete-orphan" />

In this case you may get the : not-null property references a null or transient value: com.server.X._YBackref exception.

It is because the same car is referred from two fields and both are trying to save/update.
The solution to this problem is change the preferredCar mapping as

<many-to-one name="preferredCar" class="Car" column="preferred_car_id" not-null="false" unique="true" cascade="none" />