Home Hibernate JPA Entity lifecycle - JPA developer should know

JPA Entity lifecycle – JPA developer should know

Entity Instance states

  • JPA defines four states and state transitions for the persistence life cycle.
  • Following image illustrates these states and transitions.

Transient State :

  • A newly created object and object identifier should not be there in database.
  • Objects instantiated using the new operator are not immediately persistent. Their state is “Transient”. Which means they are not associated with any database table row, and so their state is lost as soon as they are  reference removed.
  • Transient state instances state is lost and garbage-collected as soon as they are no longer referenced.

Persistent State :

  • If the object identifier is there in database table and if the object is associated with persistence-context then that object state is “Persistence State” .
  • Persistent state instances are always associated with persistence-context and transnational.
  • If we are changing persistent State object values those are synchronized automatically with the database while committing the transaction.

Detached State :

  • Object identifier should be there in database table and Object should not associated with persistence-context.
  • Instances are lose their association with persistence manager when you close() the hibernate session. We refer to these objects as detached.
  • Indicating that their state is no longer guaranteed to be synchronized with database, they are no longer under the management if their references removed, then they are eligible for garbage collector.

Removed State :

  • A persistent state entity object can also be retrieved from database and marked for deletion, by using the EntityManger’s remove() with in an active transaction. Then entity object changes its state from Persistent to Removed, and physically deleted from the database during commit.

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook



Please enter your comment!
Please enter your name here

Stay in Touch