我如何防止Hibernate更新NULL值 [英] How can I prevent Hibernate from updating NULL values

查看:408
本文介绍了我如何防止Hibernate更新NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存hibernate对象时,hibernate中是否存在一个用于忽略空值的hibernate设置?
$ b 注意 >

在我的情况下,我通过Jackson将JSON反序列化为Hibernate Pojo。


JSON只包含Pojo的一些字段。如果我保存了Pojo,那么不在JSON中的字段在Pojo中是空的,而hibernate会更新它们。



我把设置为可更新= false ,但这不是100%的解决方案。
http:// docs。 jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-property



也许有人有另一个想法...... <注意2:根据Hibernate Docs,

> dynamicUpdate 注释完全符合


dynamicInsert / dynamicUpdate(默认为false) :

指定INSERT / UPDATE SQL应该在运行时
生成,并且只包含其值不为空的列


http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-class



有趣的我如果你通过 dynamic-update 来定义它,那么docu就不会提及NULL值的含义。


dynamic-update(可选 - 默认为false):
指定UPDATE SQL应该在运行时生成,并且只能包含其值已更改的列。


由于我使用注解 AND xml配置,hibernate似乎忽略了我的 dynamicUpdate = true 注释。

解决方案

您应该首先使用DB中的主键加载对象,然后复制或反序列化JSON。



hibernate无法确定值为null的属性是否明确设置为该值,或者被排除。



如果它是一个插入,那么dynamic-insert = true应该可以工作。

Is there a setting in hibernate to ignore null values of properties when saving a hibernate object?

NOTE
In my case I am de-serializing JSON to a Hibernate Pojo via Jackson.

The JSON only contains some of the fields of the Pojo. If I save the Pojo the fields that were not in the JSON are null in the Pojo and hibernate UPDATES them.

I came accross the setting updateable=false, but this isn't a 100% solution. http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-property

Maybe somebody has another idea...

NOTE 2:

According to the Hibernate Docs the dynamicUpdate annotation does exactly that

dynamicInsert / dynamicUpdate (defaults to false):
specifies that INSERT / UPDATE SQL should be generated at runtime and contain only the columns whose values are not null.

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-class

Funny enough if you define it in XML via dynamic-update the docu do not mention the hanlding of NULL values.

dynamic-update (optional - defaults to false):
specifies that UPDATE SQL should be > generated at runtime and can contain only those columns whose values have changed.

Due to the fact that I'm using both annotations AND xml configuration, hibernate seems to ignores my dynamicUpdate=true annotation.

解决方案

You should first load the object using the primary key from DB and then copy or deserialize the JSON on top of it.

There is no way for hibernate to figure out whether a property with value null has been explicitly set to that value or it was excluded.

If it is an insert then dynamic-insert=true should work.

这篇关于我如何防止Hibernate更新NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆