Java Reference
In-Depth Information
Entity instances also become detached through cloning or serialization. This is because the
EntityManager
quite literally keeps track of entities through Java object references.
Because cloned or serialized instances don't have the same object references as the original
managed entity, the
EntityManager
has no way of knowing they exist. This scenario
occurs most often in situations where entities are sent across the network for session bean
remote method calls.
In addition, if you call the
clear
method of
EntityManager
, it forces all entities in
the persistence context to be detached. Calling the
EntityManager
's
remove
method
will also detach an entity. This makes perfect sense because this method removes the data
associated with the entity from the database. As far as the
EntityManager
is concerned,
the entity no longer exists, so there's no need to continue managing it. For your
Bid
entity,
this would be an apt demise:
manager.remove(bid);
A good way to remember the entity lifecycle is through a convenient analogy. Think of an
entity as an aircraft and the
EntityManager
as the air traffic controller. When an entity
is outside the range of air traffic control, it's “detached” or “new.” But when it does come
into range (managed), the traffic controller manages the aircraft's movement (state syn-
chronized with database). Eventually, a grounded aircraft is guided into takeoff and goes
out of airport range again (detached), at which point the pilot is free to follow their own
flight plan (modifying a detached entity without the state being managed).
The
persistence context scope
is the equivalent of airport radar range. It's critical to under-
stand how the persistence context works to use managed entities effectively. We'll examine
the relationship between the persistence context, its scope, and the
EntityManager
in
the next section.
10.1.3. Persistence context, scopes, and the EntityManager
The persistence context plays a vital role in the internal functionality of the
EntityMan-
ager
. Although you perform persistence operations by invoking methods on the
EntityManager
, the
EntityManager
itself doesn't directly keep track of the life-
cycle of an individual entity. In reality, the
EntityManager
delegates the task of man-
aging the entity state to the currently available persistence context.