Sunday, 19 August 2012

JPA Transaction Types and JTA

In the persistence.xml JPA configuration file, one has to specify the transaction type for each persistence unit:
<persistence ... >
    <persistence-unit name="..." transaction-type="RESOURCE_LOCAL">
There are two possible values: RESOURCE_LOCAL and JTA.

Resource Local

  • This is the typical value for a standalone application
  • One is responsible for the creation of the EntityManager via the EntityManagerFactory
  • Transactions are of type EntityTransaction
  • One must use begin() and commit() around every transaction
  • If multiple instances of EntityManager are created for the same persistence unit, multiple persistence contexts are created too. Meaning, transactions are NOT synchronized across these in the application. A solution is to use UserTransaction. Another is to avoid using multiple EntityManager for the same persistence unit.
// Creating resources
EntityManagerFactory EMF
    = Persistence.createEntityManagerFactory("Standalone");
EntityManager EM = EMF.createEntityManager();

// Transaction
EntityTransaction et = EM.getTransaction();

try { 
    // Operations...
} catch(Exception ex) {

// Closing resources


JTA stands for Java Transaction API. It is part of the Java EE specification. 
  • This is the typical value for a container application
  • The EntityManager is provided by the container (unique instance across the application)
  • Transactions can be declared with @TransactionAttribute and will be managed automatically
  • All transactions are synchronized over the application with a unique JTA transaction
private EntityManager EM;

public void myMethod() throws Exception {

    Item i = EM.find(Item.class, 997);

    // ...


More about JPA/JTA transactions here, more about transaction subtleties here.

No comments:

Post a comment