background image

Managing Entities

<< Table per Concrete Class Strategy | Application-Managed Entity Managers >>
<< Table per Concrete Class Strategy | Application-Managed Entity Managers >>

Managing Entities

Managing Entities
Entities are managed by the entity manager. The entity manager is represented by
javax.persistence.EntityManager
instances. Each EntityManager instance is associated
with a persistence context. A persistence context defines the scope under which particular entity
instances are created, persisted, and removed.
The Persistence Context
A persistence context is a set of managed entity instances that exist in a particular data store.
The EntityManager interface defines the methods that are used to interact with the persistence
context.
The EntityManager Interface
The EntityManager API creates and removes persistent entity instances, finds entities by the
entity's primary key, and allows queries to be run on entities.
Container-Managed Entity Managers
With a container-managed entity manager, an EntityManager instance's persistence context is
automatically propagated by the container to all application components that use the
EntityManager
instance within a single Java Transaction Architecture (JTA) transaction.
JTA transactions usually involve calls across application components. To complete a JTA
transaction, these components usually need access to a single persistence context. This occurs
when an EntityManager is injected into the application components by means of the
javax.persistence.PersistenceContext
annotation. The persistence context is
automatically propagated with the current JTA transaction, and EntityManager references that
are mapped to the same persistence unit provide access to the persistence context within that
transaction. By automatically propagating the persistence context, application components
don't need to pass references to EntityManager instances to each other in order to make
changes within a single transaction. The Java EE container manages the life cycle of
container-managed entity managers.
To obtain an EntityManager instance, inject the entity manager into the application
component:
@PersistenceContext
EntityManager em;
Managing Entities
The Java EE 5 Tutorial · September 2007
696