Friday, March 16, 2012

JPA life cycle transient persistent detached

What is the life cycle of a JPA entity?
If an entity has been defined, later on instantiated, than the life cycle of the entity begins.
The life cycle of an entity ends with remove() or a detach() (see below) method call.
An entity does not know its state of the current life cycle.
So it cannot be be queried to retrieve it's state.


What states does a JPA entity has in its lifespan?
  • transient
If a class was defined with @Entity, than  the class is an entity, so it will be used later on in the persistent context and will be managed by the Entity Manager.
As soon as this class is instantiated, it has the state transient, that means it is still a POJO, but
it will not be synchronized with the database.

  • persistent
If the method persist() is called with this entity, the entity is placed into the persistence context, that means a connection between entity and entity manager has been established.
The entity will be synchronized with the database on transaction end(commit() or flush()).

  • detached
If an entity is removed from the persistence context with the help of detach() or if the EntityManager was closed, then the connection(see above persistent) is removed. Therefore the entity will not be synchronized any longer in all cases.

A detached entity is integrated into the persistence context on calling merge().
A persistent entity can be turned into the state transient with the help of remove(), the corresponding data in the database will be deleted.


No comments:

Post a Comment