background image

Rolling Back a Container-Managed Transaction

<< Setting Transaction Attributes | Bean-Managed Transactions >>
<< Setting Transaction Attributes | Bean-Managed Transactions >>

Rolling Back a Container-Managed Transaction

Supports
: TransactionAttributeType.SUPPORTS
Never
: TransactionAttributeType.NEVER
The following code snippet demonstrates how to use the @TransactionAttribute annotation:
@TransactionAttribute(NOT_SUPPORTED)
@Stateful
public class TransactionBean implements Transaction {
...
@TransactionAttribute(REQUIRES_NEW)
public void firstMethod() {...}
@TransactionAttribute(REQUIRED)
public void secondMethod() {...}
public void thirdMethod() {...}
public void fourthMethod() {...}
}
In this example, the TransactionBean class's transaction attribute has been set to
NotSupported
. firstMethod has been set to RequiresNew, and secondMethod has been set to
Required
. Because a @TransactionAttribute set on a method overrides the class
@TransactionAttribute
, calls to firstMethod will create a new transaction, and calls to
secondMethod
will either run in the current transaction, or start a new transaction. Calls to
thirdMethod
or fourthMethod do not take place within a transaction.
Rolling Back a Container-Managed Transaction
There are two ways to roll back a container-managed transaction. First, if a system exception is
thrown, the container will automatically roll back the transaction. Second, by invoking the
setRollbackOnly
method of the EJBContext interface, the bean method instructs the
container to roll back the transaction. If the bean throws an application exception, the rollback
is not automatic but can be initiated by a call to setRollbackOnly.
Synchronizing a Session Bean's Instance Variables
The SessionSynchronization interface, which is optional, allows stateful session bean
instances to receive transaction synchronization notifications. For example, you could
synchronize the instance variables of an enterprise bean with their corresponding values in the
database. The container invokes the SessionSynchronization methods (afterBegin,
beforeCompletion
, and afterCompletion) at each of the main stages of a transaction.
The afterBegin method informs the instance that a new transaction has begun. The container
invokes afterBegin immediately before it invokes the business method.
Container-Managed Transactions
The Java EE 5 Tutorial · September 2007
1002