A single persistence context may correspond to one or more JTA entity manager instances (all associated with the same entity manager factory).
The persistence context is propagated across the entity manager instances as the JTA transaction is propagated.
Propagation of persistence contexts only applies within a local environment. Persistence contexts are NOT propagated to REMOTE tiers.
Persistence contexts are propagated by the container across component invocations as follows.
If a component is called and there is no JTA transaction or the JTA transaction is not propagated, the persistence context is not propagated.
If an entity manager is then invoked from within the component:
Invocation of an entity manager defined with PersistenceContextType.TRANSACTION will result in use of a NEW persistence context.
Invocation of an entity manager defined with PersistenceContextType.EXTENDED will result in the use of the existing extended persistence context bound to that component.
If the entity manager is invoked within a JTA transaction, the persistence context will be bound to the JTA transaction.
If a component is called and the JTA transaction is propagated into that component:
If the component is a stateful session bean to which an extended persistence context has been bound and there is a different persistence context bound to the JTA transaction, an EJBException is thrown by the container.
Otherwise, if there is a persistence context bound to the JTA transaction, that persistence context is propagated and used.
Application-managed entity manager are always EXTENDED. An injected extended persistence context is automatically associated with a JTA transaction by the EJB container. For other extended contexts created manually with the EntityManagerFactory API, you MUST call EntityManager.joinTransaction() to perform the transaction association.
Example of application-managed entity manager:
// JTA transaction is used EntityManager em = emf.createEntityManager(); ut.begin(); em.joinTransaction(); em.persist(customer); ut.commit(); em.close();
NOTE: It is NOT legal to call EntityManager.joinTransaction() if no JTA transaction is involved.
NOTE: EntityManager.joinTransaction() is required to be invoked only when an EntityManager is created explicitly using an EntityManagerFactory. If you are using EJB container-managed persistence contexts, then you DO NOT NEED to perform this extra step.