I’m using JPA2 with annotations and EclipseLink and I’m wondering if there is a difference between
EntityManager em = ...
// Some action
em.joinTransaction();
em.close();
and
EntityManager em = PU.entityManager();
em.getTransaction().begin();
// Some action
em.getTransaction().commit();
em.close();
and which one should I generally prefer?
EntityManager.joinTransactionis meant to be used for JTA transactions (implying that the persistence unit is configured to use JTA transactions) whereasEntityTransaction.beginis meant to be used for resource-local entity managers (implying the non-usage of JTA to manage transactions). Therefore, they’re both meant to be used in different scenarios.The first case, i.e.
EntityManager.joinTransactionis rarely used, for you would often inject container-managedEntityManagerinstances when you need JTA transaction support. Container-managedEntityManagers are injected (using the@PersistenceContextannotation) into the context of an existing JTA transaction (managed by the container) and hence there is no need to explicitly join a transaction. It is only in the event of application-managedEntityManagers that you need to join an existing transaction. Application managedEntityManagers are not injected by the container; instead the container may only inject anEntityManagerFactoryinstance (using the@PersistenceUnitannotation) that is used by the application to obtain theEntityManagerinstance.In the second case, i.e.
EntityTransaction.begin, no JTA transactions will be used to scope any transactional work. Instead, the transaction is resource-local in that any changes made to the persistence context are tracked as an atomic unit untilEntityTransaction.commitis invoked. One would rarely use resource-local entity managers in a Java EE application, as you would typically want EJBs (and the EJB container) to demarcate the transaction boundaries, and not the application source code. Also, any transactional work performed using a resource-local transaction will not be tracked by a JTA transaction that might already have been initiated, thereby resulting in vague , confusing and ambiguous behavior regarding the transactional activities in your application.