Hibernate does not allow me to persist an object that contains an null embedded object with an integer field. For example, if I have a class called Thing that looks like this
@Entity
public class Thing {
@Id
public String id;
public Part part;
}
where Part is an embeddable class that looks like this
@Embeddable
public class Part {
public String a;
public int b;
}
then trying to persist a Thing object with a null Part causes Hibernate to throw an Exception. In particular, this code
Thing th = new Thing();
th.id = "thing.1";
th.part = null;
session.saveOrUpdate(th);
causes Hibernate to throw this Exception
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ace.moab.api.jobs.Thing.part
My guess is that this is happening because Part is an embedded class and so Part.a and Part.b are simply columns in the Thing database table. Since the Thing.part is null Hibernate wants to set the Part.a and Part.b column values to null for the row for thing.1. However, Part.b is an integer and Hibernate will not allow integer columns in the database to be null. This is what causes the Exception, right?
So I am looking for workarounds for this problem. I noticed making Part.b an Integer instead of an int seems to work, but for reasons I won't bore you with this is not a good option for us. Thanks!
I found another workaround and thought I'd share it. Turns out that if you make the int column nullable then Hibernate doesn't throw the PropertyValueException.
@Column(nullable = true)
public Integer b;
This works for us because our hibernate enabled application is the only thing that touched the database and so we can guarantee that b is null only when the part is null. Although the null part suggestion and the use of the Integer wrapper type are great suggestions, due to lots of reasons I don't really have control over, setting the column to nullable works best for us. Thanks though and I hope this helps someone else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With