I get the following error when using a primitive attribute in my grails domain object:
Null value was assigned to a property of primitive type setter of MyDomain.myAttribute
org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of MyDomain.myAttribute
at grails.orm.HibernateCriteriaBuilder.invokeMethod(HibernateCriteriaBuilder.java:1077)
According to this SO thread, the solution is to use the non-primitive wrapper types; e.g.,
Integer
instead ofint
.There are two way
null
private int var;
can be initialized asprivate Integer var;
A null value cannot be assigned to a primitive type, like int, long, boolean, etc. If the database column that corresponds to the field in your object can be null, then your field should be a wrapper class, like Integer, Long, Boolean, etc.
The danger is that your code will run fine if there are no nulls in the DB, but will fail once nulls are inserted.
And you can always return the primitive type from the getter. Ex:
But in most cases you will want to return the wrapper class.
So either set your DB column to not allow nulls, or use a wrapper class.
Change the parameter type from primitive to Object and put a null check in the setter. See example below
Make sure your database myAttribute field contains null instead of zero.
Either fully avoid
null
in DB viaNOT NULL
and in Hibernate entity via@Column(nullable = false)
accordingly or useLong
wrapper instead of youlong
primitives.A primitive is not an Object, therefore u can't assign
null
to it.