2

I am using JPA with Hibernate. When I modify one attribute of an object and update it; the generated SQL shows all the columns getting updated ! Why doesn't it update only the modified columns? Is there a way to achieve that because I feel that will be more optimized.

Daniel Serodio
  • 4,229
  • 5
  • 37
  • 33
Deepak Singhal
  • 10,568
  • 11
  • 59
  • 98

2 Answers2

5

By default hibernate includes all the fields in the update query. If you want to exclude this either use a custom update HQL or you can configure hibernate to exclude the unmodified fields in the update query as told in this article.

This is done by adding dynamic-update="true" in your class mapping.

<class ... table="your_table" .... dynamic-update="true">

In a large table with many columns (legacy design) or contains large data volumes, this will have a great impact on the system performance. It can have some performance impact as told here. So measure the performance of your code before you implement it.

Read the API here for more information.

If you are using annotations,

@org.hibernate.annotations.Entity(selectBeforeUpdate=true)

It is a hibernate specific annotation, and not available in JPA. Here is a good article linking to the details.

Community
  • 1
  • 1
ManuPK
  • 11,623
  • 10
  • 57
  • 76
  • This works fine when using hibernate only. But I am using JPA hence I use only persistence.xml and NOT hibernate.properties. I make all declarations of my enties in persistence.xml like com.kids.domain.Child and there I am not able to use this flag – Deepak Singhal May 31 '12 at 17:13
  • @Deepak: Sorry for the delay, I have updated the answer with the details. – ManuPK Jul 15 '12 at 13:52
  • 1
    I wonder why the Hibernate team chose to update all columns by default – Daniel Serodio Oct 26 '12 at 20:24
1

I had a problem for the last 4-5 days which was slowly driving me mad.

A delete operation was using ALL columns instead of just the primary key column.

Eg.

DELETE FROM MYTABLE WHERE ID=? AND NAME=? AND VALUE=?

When I removed the "dynamicUpdate=true" annotation, Hibernate started generating the right SQL, ie.

DELETE FROM MYTABLE WHERE ID=?

It was causing nasty issues on Oracle 11g, when VALUE was a CLOB.

gnat
  • 6,213
  • 108
  • 53
  • 73
OMcGovern
  • 11
  • 1