Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent Hibernate from updating NULL values

Tags:

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.

like image 644
Jeremy S. Avatar asked Sep 22 '11 15:09

Jeremy S.


People also ask

How Hibernate handle null values?

The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table.

What is nullable false in Hibernate?

The @Column(nullable = false) Annotation It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.

How do you indicate Hibernate to not update the table?

Use updatable=false in Hibernate to avoid updating the column.

Does Hibernate update if no changes?

No. Strictly speaking, Hibernate does not send an SQL update on update .


1 Answers

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.

like image 52
gkamal Avatar answered Dec 31 '22 16:12

gkamal