1

I'm using Hibernate with Spring framework, and running into an Opportunistic Locking, so I have a fundamental question:

Does Hibernate consider the object "changed/dirty" as soon as its setter is called, for example: theEmployee.setAge(32) so even if age had already been 32, it will be considered "changed", or would Hibernate figure out that even though the setter was called, the object, effectively, has not been changed?

In other words, if I want to prevent unnecessary write's, is it necessary to code:

if (theEmployee.getAge() != age) { theEmployee.setAge(age); }

...or it is sufficient to code: theEmployee.setAge(age);

x80486
  • 6,627
  • 5
  • 52
  • 111
inor
  • 2,781
  • 2
  • 32
  • 42
  • 2
    check this link for detailed explanation http://stackoverflow.com/questions/82429/when-hibernate-flushes-a-session-how-does-it-decide-which-objects-in-the-sessio – Ankit Apr 19 '15 at 15:58

3 Answers3

5

You could test this very easily. But the answer is that Hibernate tests the actual state of the object. If the object state is the same as when it was loaded, it doesn't execute any update query.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

The framework (Hibernate) does "figure it out" and won't perform any operation(s) in the database — that's pretty awesome I have to say.

x80486
  • 6,627
  • 5
  • 52
  • 111
0

If there is any change in the object then only the update query is called in hibernate. You can have a detail look here to understand the state of object: Hibernate - State of objects

A glimpse from the above link:

States of an entity is a very important concept of Hibernate. An entity can have different states. Using Hibernate is different from using SQL. If you callsession.save(customerObject) then there is no insert into customer… query into the database. Hibernate will set the id property (if the id is generated) and bind the entity to a persistence context. The persistence context is synchronized with the database when transaction.commit() is called.

This approach has various advantages:

You can continue to update an entity and all changes to the Java object are persisted with a single database insert/update. The update of a database table row causes a row lock. Having a row lock only for a short moment at the end of a transaction, prevents locking of concurrent users or dead lock situations.

Community
  • 1
  • 1
Iqbal S
  • 1,156
  • 10
  • 16