Beans can manage their own transactions directly by communicating with the transaction service. The container provides access to the transaction manager through the UserTransaction getUserTransaction() method of javax.ejb.EJBContext.
UserTransaction is in the javax.transaction package. The sample code below illustrates the retrieval of the UserTransaction object:
SessionContext sc = ? // initialized when bean is created
...
javax.transaction.UserTransaction t = sc.getUserTransaction();
J2EE javadoc documentation
Use the J2EE javadoc documentation to view the UserTransaction object details in your browser.
The methods of UserTransaction are as follows:
begin()
Create a new transaction and associate it with the current thread
void commit()
Complete the transaction associated with the current thread
int getStatus()
Obtain the status of the transaction associated with the current thread
void rollback()
Roll back the transaction associated with the current thread
void setRollbackOnly()
Modify the transaction associated with the current thread such that the only possible outcome of the transaction is toroll back
void setTransactionTimeout(int seconds)
Modify the value of the timeout that is associated with the transactions started by the current thread in the begin method
Transaction exceptions
The exceptions that can be thrown by these methods are as follows (all extend java.rmi.RemoteException):
HeuristicCommitException
HeuristicMixedException
HeuristicRollbackException
InvalidTransactionException
NotSupportedException
RollbackException
SystemException
TransactionRequiredException
TransactionRolledbackException
For a more complete understanding of these exceptions, refer to the javax.transaction.documentation.
Class constants
The class constants that indicate the status of the transaction are as follows:
STATUS_ACTIVE
STATUS_COMMITTED
STATUS_MARKED_ROLLBACK
STATUS_NO_TRANSACTION
STATUS_PREPARED
STATUS_PREPARING
STATUS_ROLLEDBACK
STATUS_ROLLING_BACK
STATUS_UNKNOWN
These constants are returned from the getStatus() method and indicate the status of the current transaction.
Because transactions cannot be nested, an object only can partake in a single transaction at a time. getStatus() returns the current status of the current transaction.
The following diagram contains Bean managed Transactions and the session context method.
Remember to look up any of the classes and methods in the javadoc j2ee documentation. In the next lesson container-managed transactions will be discussed.