Tuesday, July 10, 2012

Persistent Object Updates and Automatic Dirty Checking

While a session remains open, if a Persistent object is modified, its data is kept synchronized with the database. The
data will be synchronized (but not committed) when session.flush() is called. It will be synchronized and committed
when the transaction is committed. It may be synchronized at other points.  For example, before Hibernate
performs some queries of the database.

For example, in the code below a change to a BallPlayer object during a session does not require any special method
call to persist the change.


Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BallPlayer p = (BallPlayer)session.get(BallPlayer.class, 1L);
p.setNickname("Bambino");
transaction.commit();  //new nickname is synch’ed and committed here
session.close();


Hibernate knows and tracks the Persistent object and its state change. Merely committing the transaction will cause
the new data to be synchronized to the database with an update statement.


Update Player set name=?, nickname=?, date_of_birth=?,
city_of_birth=?, uniform_number=? Where id=?


Hibernate monitors all Persistent objects (i.e. the persistent context). At the end of a unit of work, it knows which
objects have been modified. It then calls update statements on all updated objects. This process of monitoring and
updating only objects that have changed is called
automatic dirty checking. As opposed to updating all Persistent
objects at the end of each work, automatic dirty checking can offer significant performance savings.

No comments: