Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid "Hibernate exception Null value was assigned to a property of primitive type setter" without wrappers

Having a long field on an entity managed by hibernate could be dangerous with null values. When Hibernate tries to set a null into a primitive an exception will be thrown.

Best solution should be to use Long instead of long, so null can be assigned to Long field.

But, I'm working on a project where we can't use Long or Integer types. I'm wondering if there is a way to override hibernate types to use a nullSafe method or something like that.

like image 553
ilopezluna Avatar asked Feb 06 '15 09:02

ilopezluna


People also ask

Why do I get a null value was assigned to a property of primitive type setter of?

This is a pretty informative error message. Primitive types cannot be null. So if you're performing a load from the DB, and the field doesn't have a NOTNULL constraint, you can have null values, which Hibernate will attempt to assign to your variable of primitive type.

How hibernate handle null values?

The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table. Auto-boxing is your friend.

Can you set primitive type to null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.


1 Answers

At finally I've get it implementing UserTypeof hibernate as explained here: http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom

like image 199
ilopezluna Avatar answered Sep 20 '22 12:09

ilopezluna