How can I prevent Hibernate from updating NULL values

Jeremy S. picture Jeremy S. · Sep 22, 2011 · Viewed 20.1k times · Source

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.

Answer

gkamal picture gkamal · Sep 22, 2011

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.