Card 01/ 07

ConceptDifficulty: Advanced1 min

JPA Entity States: Transient, Managed, Detached and Removed

Whether changing a field does anything depends on which of four states the object is in.

A JPA entity is always in exactly one of four states: transient, managed, detached or removed. The state says whether the persistence context (JPA's record of the entities it is tracking in the current transaction) is watching the object, and so whether changing it will reach the database.

new Employee("Alex") produces an object that the database knows nothing about. Setting a field on it is as inert as setting a field on any other Java object: nothing tracks it and nothing will be written. The same Employee, once loaded with find(), behaves differently, because now it is tracked.

The four entity states
StateMeans
TransientJust an object: created with new, never persisted, not tracked
ManagedThe persistence context is tracking it, and changes are written automatically
DetachedIt was managed once, and the persistence context has stopped watching it
RemovedMarked for deletion; the row disappears when the transaction commits

The EntityManager operations, JPA's interface for loading and saving entities, move an entity from one state to another:

The four entity states and the operations that move between them

persist() and find() make an entity managed, detach() and clear() stop the tracking, merge() brings a detached entity's state back into the persistence context, and remove() marks a managed entity for deletion. A managed entity also becomes detached when its persistence context closes, usually at the end of the transaction.

So the useful question about an entity is never "is it saved?" but "which of the four states is it in right now?". The answer tells you whether the next change to it will be written.

← → move through sections and cards