state with the database when possible. We'll explore exactly how the entity lifecycle looks
in the following section.
10.1.2. Lifecycle of an entity
An entity has a pretty simple lifecycle. Making sense of the lifecycle is easy once you grasp
a straightforward concept: the EntityManager knows nothing about a POJO, regard-
less of how it's annotated, until you tell the manager to start treating the POJO like a JPA
entity. This is the exact opposite of POJOs annotated to be session beans or MDBs, which
are loaded and managed by the container as soon as the application starts. Moreover, the
default behavior of the EntityManager is to manage an entity for as short a time as pos-
sible. Again, this is the opposite of container-managed beans, which remain managed until
the application is shut down.
An entity that the EntityManager is keeping track of is considered attached or man-
aged . On the other hand, when an EntityManager stops managing an entity, the entity
is said to be detached . An entity that was never managed at any point is called transient or
new . Figure 10.2 summarizes the entity lifecycle.
Figure 10.2. An entity becomes managed when you persist, merge, or retrieve it. A managed entity becomes
detached when it's out of scope, removed, serialized, or cloned.
Let's take a close look at the managed and detached states.