开发者

Is there a difference between getTransaction().begin()/.commit() and joinTransaction() with JPA2/EclipseLink?

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.joinTransaction is meant to be used for JTA transactions (implying that the persistence unit is configured to use JTA transactions) whereas EntityTransaction.begin is 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.joinTransaction is rarely used, for you would often inject container-managed EntityManager instances when you need JTA transaction support. Container-managed EntityManagers are injected (using the @PersistenceContext annotation) 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-managed EntityManagers that you need to join an existing transaction. Application managed EntityManagers are not injected by the container; instead the container may only inject an EntityManagerFactory instance (using the @PersistenceUnit annotation) that is used by the application to obtain the EntityManager instance.

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 until EntityTransaction.commit is 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜