Hibernate does not allow an embedded object with an int field to be null?
You're absolutely right about what's happening. When an object of an embedded class is null, Hibernate represents this by making all its columns null in the database; unfortunately, this means Hibernate can't tell the difference between a null embeddable object and an embeddable object with all null values.
As far as I know, if you can't make the field nullable (by making it an Integer
, as you guessed), the only way around this is to create a custom Hibernate type. Should be doable, but it'll be a pain to do it that way. In fact, it'd likely be worse than whatever the reason is you can't use an Integer — so what is that reason, anyway?
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.
Pretty uncomfortable, yes. You can set a default value to the part
field:
private Part part = new Part();
or even
private Part part = Part.NULL_PART;
(see Null object patern)
Bear in mind, that if your @Embeddable
class does not contain a primitive (which has a default value), and you save an object with all null
s, the whole structure will be persisted in the database as null
, because there isn't a way for hibernate to make the difference in the DB whether you don't have an object, or you have an empty one. To workaround this, if it arises, you'd have to create a dummy field (boolean
is best).