JPA Tutorial - Entity Object Life Cycle

In this quick tutorial, we will discuss the JPA entity life cycle states with a diagram.

Java Persistence API (JPA) provides a specification for managing the relational data in applications.
JPA specifications are defined with annotations in a javax.persistence package. Using JPA annotation helps us in writing implementation-independent code.

Learn complete JPA at JPA Tutorial - Java Persistence API
JPA entity objects are in-memory instances of entity classes (persistable user-defined classes), which can represent physical objects in the database.

Entity Object Life Cycle

The life cycle of entity objects consists of four states: New, Managed, Removed and Detached.

New state

When an entity object is initially created its state is New.  In this state, the object is not yet associated with an EntityManager and has no representation in the database.

Managed state

An entity object becomes Managed when it is persisted to the database via an EntityManager’s persist method, which must be invoked within an active transaction. On transaction commit, the owning EntityManager stores the new entity object to the database. 

Entity objects retrieved from the database by an EntityManager are also in the Managed state. 

If a managed entity object is modified within an active transaction the change is detected by the owning EntityManager and the update is propagated to the database on transaction commit.  

Removed state

A managed entity object can also be retrieved from the database and marked for deletion, using the EntityManager’s remove method within an active transaction. The entity object changes its state from Managed to Removed and is physically deleted from the database during commit.

Detached state


The last state, Detached, represents entity objects that have been disconnected from the EntityManager. For instance, all the managed objects of an EntityManager become detached when the EntityManager is closed. 

Learn JPA at https://www.javaguides.net/p/jpa-tutorial-java-persistence-api.html.

References

https://www.javaguides.net/p/jpa-tutorial-java-persistence-api.html


Comments