Codementor Events

Life Cycle of an entity object & Dirty Checking in Hibernate

Published Jul 28, 2018

Before goin deep down in this topic, i just want to define some term beforehand so that while understanding this scenario you will be able to quickly pick-up those terms.

Persistence Context :- Basically it's a Cache, which manages the states of persistent objects means it manages the lifecycle of an entity objects and defines there scopes.

LifeCycle of an Entity Object :- Each Entity object has basically 3 States:

  1. New, or Transient :- When the object is in a Transient state it doesn’t represent any row of the database, i mean not associated with any Session object, if we speak more we can say no relation with the database its just an normal object.

  2. Managed, or Persistent :- When an object represents any row of the database means it is associated with Session object, it's called persistence state.

  3. Detached :- Object previously having relation with the database, now not associated with any Session object is in detached state.

What is Dirty Checking?
Hibernate has a feature of checking all managed entity properties. Whenever an entity is loaded through hibernate, it makes an additional copy of that whole entity object along with the all entity's property values. By entity, we mean each persistent object of that entity type.

So even if only one property of the persistent object is changed, Hibernate will still check all managed entities. It detects which objects have been modified and then calls update statements on all updated objects.

A transaction is performed with the help of the session. Session object helps in fetching the transaction object. So while a session remains open and if a persistent object is modified, its data is kept synchronized with database. The data will be synchronized but will not be committed, till session's flush() method is called. Both synchronization and committing of code will happen together when the code is committed. It will also be synchronized at some other points too.

Hibernate monitors all persistent objects. At the end of a unit of work, it knows which objects have been modified. Then it calls update statement on all updated objects. This process of monitoring and updating only objects that have been changed is called automatic dirty checking in hibernate.

How does this happens?
Within the Persistence Context, Hibernate has a copy of all persistent objects that were loaded from the database. It compares these persistent objects with these objects to detect the objects that have been modified or are dirty. This is the default implementation.

At the end of the transaction, Hibernate acquires a proper table locks, updates the specific record and releases the lock thereby completing the transaction.

Thank You For Reading:)

Discover and read more posts from Narendra Sharma
get started