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()?
If you use container managed
EntityManagerthen you’re using JTA transactions. Hence, you don’t need to (more precisely – you can not) interfere withEntityManager‘s transactions fetched usingentityManager.getTransaction(). The JTA starts and commits your transaction.If you use application managed
EntityManagerand 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
EntityManagerwhich works withEntityManager.getTransaction()is used in Java SE environment.EDIT: You might be interested in secion 7.5 Controlling Transactions from the JPA 2.0 specification.