O'Reilly logo

Java EE 7 Essentials by Arun Gupta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 12. Java Transaction

The Java Transaction API (JTA) is defined as JSR 907, and the complete specification can be downloaded.

The JTA specifies local interfaces between a transaction manager and the parties involved in a distributed transaction system: the application, the resource manager, and the application server.

The API defines a high-level interface, annotation, and scope to demarcate transaction boundaries in a transactional application.

User-Managed Transactions

The UserTransaction interface enables the application to control transaction boundaries programmatically. This interface is typically used in EJBs with bean-managed transactions (BMT).

You can obtain UserTransaction using injection:

@Inject UserTransaction ut;

or through a JNDI lookup using the name java:comp/UserTransaction:

Context context = new InitialContext();
UserTransaction ut = (UserTransaction)context.lookup("java:comp/UserTransaction");

The begin method starts a global transaction and associates the transaction with the calling thread. The commit method completes the transaction associated with the current thread. All statements within begin and commit execute in the transaction scope:

ut.begin();
//. . .
ut.commit();

When the commit method completes, the thread is no longer associated with a transaction.

A transaction can be rolled back via the rollback method:

ut.begin();
//. . .
ut.rollback();

When the rollback method completes, the thread is no longer associated with a transaction.

You can change the timeout ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required