Java Reference
In-Depth Information
Managed entities
When we talk about managing an entity's state, what we mean is that the EntityMan-
ager makes sure that the entity's data is synchronized with the database. The
EntityManager ensures this by doing two things. First, as soon as you ask an
EntityManager to start managing an entity, it synchronizes the entity's state with the
database. Second, until the entity is no longer managed, the EntityManager ensures
that changes to the entity's data (caused by entity method invocations, for example) are
reflected in the database. The EntityManager accomplishes this feat by holding an ob-
ject reference to the managed entity and periodically checking for data freshness. If the
EntityManager finds that any of the entity's data has changed, it automatically syn-
chronizes the changes with the database. The EntityManager stops managing the entity
when the entity is either deleted or moves out of the persistence provider's reach.
An entity can become attached to the EntityManager 's context when you pass the en-
tity to the persist or merge methods. An entity also becomes attached when you re-
trieve using the find method or a query within a transaction. The state of the entity de-
termines which method you'll use. A managed entity can always be immediately refreshed
with the latest database data by calling the refresh method.
When an entity is first instantiated, as in the following snippet, it's in the new or transient
state because the EntityManager doesn't know it exists yet:
Bid bid = new Bid();
Therefore, the entity instance isn't managed yet. It'll become managed if the
EntityManager 's persist method creates a new record in the database correspond-
ing to the entity. This would be the most natural way to attach the Bid entity in the previ-
ous snippet to the EntityManager 's context:
A managed entity becomes detached when it's out of scope, removed, serialized, or cloned.
For example, the instance of the Bid entity will become detached when the underlying
transaction commits.
Search WWH ::

Custom Search