避免“Hibernate异常将Null值分配给基本类型setter的属性”而不使用包装器

时间:2015-02-06 09:14:00

标签: java hibernate hibernate-mapping hbmxml

在hibernate管理的实体上有一个长字段,对于null值可能会很危险。当Hibernate尝试将null设置为原语时,将抛出异常。

最佳解决方案应该是使用Long而不是long,因此可以将null分配给Long字段。

但是,我正在开展一个我们不能使用Long或Integer类型的项目。我想知道是否有办法覆盖hibernate类型以使用nullSafe方法或类似的东西。

2 个答案:

答案 0 :(得分:2)

最后我已经实现了UserType hibernate,如下所述:http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch06.html#types-custom

答案 1 :(得分:-1)

我总是使用封装的类类型,但是如果你不能检查实体属性,那么可以坚持下去:

if (entity.getAttribute == null){
entity.setAttribute(0); //case of long, int...
}