9

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.

Ignasi
  • 5,887
  • 7
  • 45
  • 81

2 Answers2

2

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

Ignasi
  • 5,887
  • 7
  • 45
  • 81
-1

I always use encapsulated class types, but if you can't you can check the entity attributes before persist it something like:

if (entity.getAttribute == null){
entity.setAttribute(0); //case of long, int...
}
  • yeah me to in fact, but the problem is on data which is already in the database, so it's not an option (update the stored data is not an option too) – Ignasi Feb 06 '15 at 18:28
  • This will not compile if the return type of `entity.getAttribute()` is `int` or `long`. Further, the problem the OP is having is that the hibernate library *itself* is attempting to call a *setter* with `null`. – Ian McLaird Feb 06 '15 at 18:33