Search This Blog

Tuesday 14 February 2012

The Hibernate Object Life-Cycle

The Hibernate framework is used to mange the persistence of objects. It allows objects to be associated with data present in the tables. It saves/modifies and inserts records in the database tables based on values in these objects and the operations performed on them using the Hibernate interfaces.
In the sequence of these operation calls, the data objects exist in various states. These states and the transition from one state to another forms the persistence life cycle.
I picked up the diagram from the book "Java Persistence With Hibernate". It provides a very good explanation of the life cycle the objects go through as a part of their association with the Hibernate layer.
 I executed the below code to pass an object through the entire persistence life cycle:
public static void testEntityLifeCycle() {
    Entity entity = new Entity(); //new object created; in Transient state
    entity.setData("New Data 1");
    Session session = sessionFactory.openSession();
    System.out.println("Session (object is transient): " + session);
    Transaction transaction = session.beginTransaction();
    session.save(entity);// Object now in persistent state
    System.out.println("The object id is " +entity.getId());
    System.out.println("Session (after Object save): " + session);                
    transaction.commit();
    session.close();
    System.out.println("Session (after close): " + session);
    
    //here object is in detached state
    session = sessionFactory.openSession();
    session.saveOrUpdate(entity);
    //object is now in persistent state again
    System.out.println("Session (new one): " + session);
    transaction = session.beginTransaction();
    session.delete(entity);
    //the entity is now in removed state
    transaction.commit();
    System.out.println("Session (after Object deletion): " + session);
    session.close();
}// object available for garbage collection at
//end of this method
When the new Entity object is created it is in the transient state.The object is not associated with Hibernate session.
2656 [main] DEBUG org.hibernate.impl.SessionImpl  - opened session at timestamp:
 13198936161
Session (object is transient): SessionImpl(PersistenceContext[entityKeys=[],coll
ectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreat
ions=[] collectionRemovals=[] collectionUpdates=[]])
The session.save method causes Hibernate to save the object in the database table. It also assigns a primary key to the id property. The object is now in the persistent state.Persistent instances are always associated with a persistence Context.
This object is visible in the session object that is displayed after the save call. The Entity can now be seen as a part of the persistence context.
2672 [main] DEBUG org.hibernate.jdbc.JDBCContext  - after transaction begin
2687 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - sa
ving transient instance
2687 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - saving [c
om.model.Entity#<null>]
2718 [main] DEBUG org.hibernate.SQL  - 
    insert 
    into
        Entity
        (DATA) 
    values
        (?)
...
The object id is 1
Session (after Object save): SessionImpl(PersistenceContext[entityKeys=[EntityKe
y[com.model.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] d
eletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
2609 [main] DEBUG org.hibernate.transaction.JDBCTransaction  - commit
After the session is closed, the objects are removed from the session. The entity object now moves back to the detached state. It still holds persistent data, but there is no guarantee that this data will continue to be in sync with the table data.
2781 [main] DEBUG org.hibernate.impl.SessionImpl  - closing session
...
Session (after close): SessionImpl(<closed>)
It is also possible to return the object back to the persistent state.In our code we created a new session and associated the detached object to this session instance.
2781 [main] DEBUG org.hibernate.impl.SessionImpl  - opened session at timestamp:
 13198936163
2781 [main] DEBUG org.hibernate.event.def.AbstractSaveEventListener  - detached 
instance of: com.model.Entity
2781 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - up
dating detached instance
2797 [main] DEBUG org.hibernate.event.def.DefaultSaveOrUpdateEventListener  - up
dating [com.model.Entity#1]
Session (new one): SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.mode
l.Entity#1]],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] 
collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
...
2828 [main] DEBUG org.hibernate.SQL  - 
    update
        Entity 
    set
        DATA=? 
    where
        id=?
The call to delete will ensure that the object is deleted from the database table. The object now moves from the persistent state to removed state. There is no identifier associated with this object. The state of the object is similar to those in transient state.
2843 [main] DEBUG org.hibernate.SQL  - 
    delete 
    from
        Entity 
    where
        id=?
...
2843 [main] DEBUG org.hibernate.impl.SessionImpl  - after transaction completion
Session (after Object deletion): SessionImpl(PersistenceContext[entityKeys=[],co
llectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCre
ations=[] collectionRemovals=[] collectionUpdates=[]])
At the end of method, the object is now ready to be garbage collected, thus ending the persistence life-cycle of this object.
There are a lot of other methods in the diagram. There are several more methods in Hibernate which could be part of the above diagram( for r.g. Criteria methods) However we shall cover these in upcoming posts.

10 comments:

  1. Sometimes your blog is loading slowly better find a better host.

    ReplyDelete
  2. I like it very much because it has very helpful articles of various topics like different culture and the latest news. I am a googler and search on many topics. By searching i found this nice website. Thanks for sharing.

    ReplyDelete
  3. good one ..... quick update on states

    ReplyDelete
  4. Good Article.. Precise and informative in short..

    ReplyDelete
  5. This comment has been removed by a blog administrator.

    ReplyDelete
  6. Assetto corsa server is usually one of the most performance-sensitive aspects of a game architecture

    ReplyDelete