Card 01/ 07

ConceptDifficulty: Advanced1 min

Four States, One Object

new Employee("Alex") produces an object. Nothing about the database knows it exists yet, and setting a field on it is exactly as inert as setting a field on any other plain object — nothing is being tracked, nothing will be written anywhere.

A JPA entity is always in exactly one of four states, and which one decides whether touching it does anything at all.

The four entity states
StateMeans
TransientJust an object — new, never persisted, not tracked
Managed (persistent)The persistence context is tracking it; changes are picked up automatically
DetachedWas managed once; the persistence context has stopped watching it
RemovedMarked for deletion; the row disappears when the transaction commits
The four entity states and the operations that move between them

So the question that actually matters is never "is this saved?" — it's "which of the four states is this object in right now?" The rest of this topic is the operations named on the diagram, and what each one actually does.