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" />



1 comment:

  1. Hm, very interesting method of solution this problem, I will take a note. But I know another one method of solution, that I have read here about transient variable java https://explainjava.com/java-transient/ and its really helped me a lot.

    ReplyDelete