javagoogle-app-enginejpatransactions

JPA - When to use getTransaction() when persisting objects


I've recently started working with JPA on the Google App Engine. In reading some examples, I've noticed a couple of variations in the way objects are persisted. In one case, I've seen something like this:

entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();

In other cases, I don't see the use of getTransaction(). I simply see entityManager.persist(object). When is it appropriate to use getTransaction()?


Solution

  • If you use container managed EntityManager then you're using JTA transactions. Hence, you don't need to (more precisely - you can not) interfere with EntityManager's transactions fetched using entityManager.getTransaction(). The JTA starts and commits your transaction.

    If you use application managed EntityManager and you don't want to be in part of JTA transaction, then you need to manage them for yourself (it's called a resource-local entity manager).

    Most typically, application managed EntityManager which works with EntityManager.getTransaction() is used in Java SE environment.

    EDIT: You might be interested in secion 7.5 Controlling Transactions from the JPA 2.0 specification.