Hibernate Persistence/Entity object life cycle

Persistence Object has three life cycle states
1. Transient state
2. Persistent state
3. Detached state

Lifecycle/State Is object associated with the session? Is object present in database?
Transient NO NO
Persistent YES YES
Detached NO YES

Transient state: Object is neither associated with Session nor present in Database.

Persistent state: Object is associated with Session and also present in Database.

Detached state: Object is not associated with Session, but present in Database.

Transient state Example:

EMPLOYEE table

EMP ID EMP NAME EMP SALARY
1001 Sachin 50000
1002 Rahul 40000

Application code:

 

  • Here emp object is not associated with session and there is no matching record in the Employee table. So emp object is in TRANSIENT
  • In this state, object is non-transactional. That means object is not synchronized with table record in database.
  • In this state, changes made to Objects don’t save into the database.

Persistent state Example:

EMPLOYEE table

EMP ID EMP NAME EMP SALARY
1001 Sachin 50000
1002 Rahul 40000

Application code:

 

  • Here emp object is associated with session and there is matching record in EMPLOYEE. So emp object is in PERSISTENET state.
  • Here object is transactional. That means object is synchronized with table record in database. Here modifications which are done to the entity, doesn’t save into the database.
  • Changes made to objects are automatically saved into the database without invoking session persistence methods.

Detached state Example:

EMPLOYEE table

EMP ID EMP NAME EMP SALARY
1001 Sachin 50000
1002 Rahul 40000

Application code:

 

  • Here emp object becomes Detached state from persistent state after calling session.close().
  • Changes made to object will not be stored into database, Since session is closed (garbage collected)
  • Here object is non-transactional, that means object is not synch with database. So changes made to detached objects are not saved into the database.

 

 

 

Posted in hibernate and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">