Distributed Transactions   «Prev  Next»
122
Lesson 10 Session beans and transactions
ObjectiveManipulate the transaction from within the session bean.

Session Beans and Transactions

Even when a session bean is not managing its own transactions, it can affect the outcome of current transactions.
The bean does this in two ways: through
  1. the SessionSynchronization interface and
  2. through the EJBContext.

SessionSynchronization

A session bean can execute with the context of a transaction that it is not managing. The transaction manager notifies the bean of the steps it is taking regarding the transaction.
It does this through the SessionSynchronization interface, which is implemented by the bean:

public class BankAccountBean 
implements SessionSynchronization {
.  .  .
}

The methods of the SessionSynchronization are as follows:
  1. void afterBegin()
  2. void beforeCompletion()
  3. void afterCompletion(committed boolean)

The transaction manger (TM) calls these methods at the appropriate time. afterBegin() is called just after the TM starts the transaction and before it does anything else. beforeCompletion() is called just before the TM commits the transaction.
afterCompletion() is called after the transaction was completed.
The argument indicates if the transaction was successful (TRUE) or rolled back (FALSE). Notice that these methods do not allow the bean to change the outcome of the transaction. However, they do allow the bean instance to write its data, if it has any, to the persistent store just after beforeCompletion(). It allows synchronization of the private data in the bean instance with the overarching transaction.

EJBContext

The session bean instance can get involved in the outcome of the current transaction of which it is a part. EJBContext provides the following methods:

public interface EJBContext { 
boolean getRollbackOnly();
void setRollbackOnly();
. . .
}

These methods allow the bean to request that the transaction be rolled back, or to find out whether it was rolled back or not.getRollbackOnly() returns true, only if the outcome the transaction is rollback. When setRollbackOnly() is called, the only outcome of the transaction is rollback. These methods are valid for both bean-managed and container-managed transactions.