Search This Blog

Thursday, 16 February 2012

The Hibernate Persistence Context

In our previous post we saw the object cycle and how the Hibernate session kept a tab on all the persistent objects. A call to session.toString() returns the following:
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.mode
l.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[
] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
There is something inside the Hibernate session called the PersistenceContext. What is it ?
If we look into the Hibernate source code of the Session implementation(org.hibernate.impl.SessionImpl) we can see the following variable:
public final class SessionImpl extends AbstractSessionImpl
        implements EventSource, org.hibernate.classic.Session, JDBCContext.Context {
...
private transient StatefulPersistenceContext persistenceContext;
...
}
The code level comments for the class is as below:
" A PersistenceContext represents the state of persistent "stuff" 
which Hibernate is tracking. This includes persistent entities, collections, 
as well as proxies generated.
There is meant to be a one-to-one correspondence between a SessionImpl and a 
PersistentContext. The SessionImpl uses the PersistentContext to track the 
current state of its context. Event-listeners then use the PersistentContext to 
drive their processing."
As stated above every Hibernate session is associated with a single persistence context. This class is like a large cache that holds all loaded entity instances, loaded proxies, arrays and collections. It also includes a set of all deleted entities in this session, associations that Hibernate tried to load, and did not find in the database etc. More simply put, the Persistence Context is aware of all the Persistent objects loaded in a session.
It also keeps track of entities to be loaded via batch fetching, collections that were loaded without loading the parent object and so much more.
The point is most of Hibernate's smart behavior and optimizations like automatic dirty checking, transactional write behind and first level caching are made possible by this class. Even in JPA a similar class is used to manage these functionalities.

1 comment:

  1. Excellent Article. Explained relationship between Session and Persistence Context of Hibernate.

    ReplyDelete