Sunday, October 2, 2016

Dirty loading/checking in Hibernate

Every Hibernate session is cached.

It caches entities read from the database, changes made to entities, as well as added and removed entities; until the session is flushed (ie written to the database).

A session is said to be dirty when some changes have not yet been flushed. This session is flushed before the transaction is committed. It is perfectly normal to have a dirty session.

In simple words: Dirty data is the one which is not yet committed. Similarly, dirty session in hibernate contains modified data which is not yet committed :)

Configuration con = new Configuration();
con.configure("dirty.cfg.xml");
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction trans = session.beginTransaction();

try
{
   Gender gender = (Gender)session.get(Gender.class, new Long(1));
   gender.setName("someName");
   session.getTransaction().commit();
   session.flush();
}
catch(Eception ex)
{
  ex.printStackTrace();
}

Here, we have not called update(), even then object state is written to the database. This is called automatic dirty checking

Hibernate monitors whether any changes are made in the session object and automatically synchronizes them to the database.

session.getTransaction.commit() is mandatory, else correct data will not reflect in the database.

No comments:

Post a Comment

Home