Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore null values of entity bean while updating the table using Hibernate

Tags:

java

hibernate

Stuck on the same problem Is there any method to ignore null values when updating the database in Hibernate?

Whenever you call update(); of Session, it will also update the null values found in the object.

Example:

User user = new User();
user.setUserId(5);
user.setUserName("Maarten");
user.setUserFirstName(null); // but in database this value is not null

session.update( user);

OR

session.saveOrUpdate( user);

The DB will now update the user, but will set the user firstname to null (because it is null in the object).

Is there any way or method in Hibernate to avoid this (I don't want to fire a select/ update query to set the bean)? that it will ignore the null value?

like image 399
Vishrant Avatar asked Apr 25 '14 06:04

Vishrant


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. Auto-boxing is your friend.

How does JPA handle null values?

The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.

Does Hibernate Query List return null?

When there are no rows, both query. list() and criteria. list() are returning empty list instead of a null value.

Does Hibernate update if no changes?

Hibernate always updates all database columns mapped by my entity, even the ones that I didn't change.


2 Answers

hibernate-dynamic-update

The dynamic-update attribute tells Hibernate whether to include unmodified properties in the SQL UPDATE statement.

like image 152
Gundamaiah Avatar answered Oct 09 '22 01:10

Gundamaiah


One of the options is, load the bean using get(object) method from the session and then set/change the values. But this comes with an overhead of one extra call to the database. Or you can create a custom query if making an extra call is crucial.

Edit: if bean is cached then get(object) will not be a performance hit.

like image 44
Vishrant Avatar answered Oct 09 '22 02:10

Vishrant