background image

Application-Managed Entity Managers

<< Managing Entities | Persisting Entity Instances >>
<< Managing Entities | Persisting Entity Instances >>

Application-Managed Entity Managers

Application-Managed Entity Managers
With application-managed entity managers, on the other hand, the persistence context is not
propagated to application components, and the life cycle of EntityManager instances is
managed by the application.
Application-managed entity managers are used when applications need to access a persistence
context that is not propagated with the JTA transaction across EntityManager instances in a
particular persistence unit. In this case, each EntityManager creates a new, isolated persistence
context. The EntityManager, and its associated persistence context, is created and destroyed
explicitly by the application.
Applications create EntityManager instances in this case by using the createEntityManager
method of javax.persistence.EntityManagerFactory.
To obtain an EntityManager instance, you first must obtain an EntityManagerFactory
instance by injecting it into the application component by means of the
javax.persistence.PersistenceUnit
annotation:
@PersistenceUnit
EntityManagerFactory emf;
Then, obtain an EntityManager from the EntityManagerFactory instance:
EntityManager em = emf.createEntityManager();
Finding Entities Using the EntityManager
The EntityManager.find method is used to look up entities in the data store by the entity's
primary key.
@PersistenceContext
EntityManager em;
public void enterOrder(int custID, Order newOrder) {
Customer cust = em.find(Customer.class, custID);
cust.getOrders().add(newOrder);
newOrder.setCustomer(cust);
}
Managing an Entity Instance's Life Cycle
You manage entity instances by invoking operations on the entity by means of an
EntityManager
instance. Entity instances are in one of four states: new, managed, detached, or
removed.
New entity instances have no persistent identity and are not yet associated with a persistence
context.
Managing Entities
Chapter 24 · Introduction to the Java Persistence API
697