user manual
Chapter 19: Transaction management 207
Programmatic transaction management using JTA APIs
about transaction synchronization and implements the
javax.ejb.SessionSynchronization interface, then the Assembler/Deployer can
specify only the attributes Required, RequiresNew, or Mandatory. These attributes
ensure that the container invokes the bean only within a global transaction,
because transaction synchronization can only occur within a global
transaction.
Programmatic transaction management using JTA APIs
All transactions use the Java Transaction API (JTA). When transactions are
container managed, the platform handles the demarcation of transaction
boundaries and the container uses the JTA API; you do not need to use this
API in your bean code.
A bean that manages its own transactions (bean-managed transaction),
however, must use the JTA javax.transaction.UserTransaction interface. This
interface allows a client or component to demarcate transaction boundaries.
Enterprise JavaBeans that use bean-managed transactions use the method
EJBContext.getUserTransaction().
In addition, all transactional clients use JNDI to look up the UserTransaction
interface. This simply involves constructing a JNDI InitialContext using the
JNDI naming service, as shown in the following line of code:
javax.naming.Context context = new javax.naming.InitialContext();
Once the bean has obtained the InitialContext object, it can then use the
JNDI lookup() operation to obtain the UserTransaction interface, as shown in the
following code sample.
javax.transaction.UserTransaction utx = (javax.transaction.UserTransaction)
context.lookup("java:comp/UserTransaction");
Note that an EJB can obtain a reference to the UserTransaction interface from
the EJBContext object. This is because an enterprise bean by default inherits a
reference to the EJBContext object. Thus, the bean can simply use the
EJBContext.getUserTransaction() method rather than having to obtain an
InitialContext object and then using the JNDI lookup() method. However, a
transactional client that is not an enterprise bean must use the JNDI lookup
approach.
When the bean or client has the reference to the UserTransaction interface, it
can then initiate its own transactions and manage these transactions. That is,
you can use the UserTransaction interface methods to begin and commit (or
rollback) transactions. You use the begin() method to start the transaction,
then the commit() method to commit the changes to the database. Or, you use
the rollback() method to abort all changes made within the transaction and
restore the database to the state it was in prior to the start of the transaction.
Between the begin() and commit() methods, you include code to carry out the
transaction's business.










