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">
        ...
    </persistence-unit>
    ...
</persistence>
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.
Usage:
// Creating resources
EntityManagerFactory EMF
    = Persistence.createEntityManagerFactory("Standalone");
EntityManager EM = EMF.createEntityManager();

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

try { 
    et.begin();
    // Operations...
    et.commit();
} catch(Exception ex) {
    et.rollback();
}

// Closing resources
EM.close();
EMF.close();

JTA

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
Usage:
@PersistenceContext(unitName="Container")
private EntityManager EM;

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void myMethod() throws Exception {

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

    // ...

}

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