2

From this SO answer:

The update() method forces an update to the persistent state of the object in the database, always scheduling an SQL UPDATE. ... It doesn’t matter if the item object is modified before or after it’s passed to update(). ... Hibernate always treats the object as dirty and schedules an SQL UPDATE., which will be executed during flush. On the other hand, merge() queries the database first, and doesn't perform update if state haven't changed.

A doubt emerged in my mind:
How is Hibernate (or any JPA implementation) able to tell if the state of an entity has changed so that an update operation is needed ?
Should we implement equals or hashcode method to help Hibernate to do so ? What if do not implement those methods ?

Alexander Petrov
  • 9,204
  • 31
  • 70
GionJh
  • 2,742
  • 2
  • 29
  • 68

1 Answers1

6

There are two mechanisms for dirty checking in Hibernate. JPA is specification and it is up to the providers to figure out how the will do it. In the case of hibernate:

First one is the default No Proxy mechanism where the hibernate session is keeping a copy of each objects and compares this copy to everything that is submitted through the EntityManager for update.

The second mechanism is if you use Instrumentation on the Hibernate entities. In which case everything is wrapped in a proxy. In this case hibernate does not compare the object itself but instead overtime you modify a value the Proxy ensures that the entity is marked as dirty.

Here is one site describing the two approaches in details: https://vladmihalcea.com/the-anatomy-of-hibernate-dirty-checking/

Alexander Petrov
  • 9,204
  • 31
  • 70
  • 1
    hehe here we are again :-) What if I merge a detached Object ? – GionJh Jul 18 '16 at 20:56
  • 1
    How does Hibernate know if the detached entity is equals or not to the corresponding entity on the DB ? – GionJh Jul 18 '16 at 20:58
  • It does not, this is why you have optimistic locking. First it checks if a managed object exists with the same identity. If exists it applies the changes and try to save it. If the save succeed than obviously the data is not stale. If it does not a staleobjectexception will be thrown most probably. The second scenario is if a managed object does not exist. This results in SQL select. – Alexander Petrov Jul 18 '16 at 21:05
  • Here is a link with more details on the merge algorithm if you are interested http://techblog.bozho.net/how-does-merge-work-in-jpa-and-hibernate/ – Alexander Petrov Jul 18 '16 at 21:05