Container-Managed Transactions
In an enterprise bean with container-managed transaction demarcation, the EJB container sets the boundaries of the transactions. You can use container-managed transactions with any type of enterprise bean: session, or message-driven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction's boundaries. The code does not include statements that begin and end the transaction.
By default if no transaction demarcation is specified enterprise beans use container-managed transaction demarcation.
Typically, the container begins a transaction immediately before an enterprise bean method starts. It commits the transaction just before the method exits. Each method can be associated with a single transaction. Nested or multiple transactions are not allowed within a method.
Container-managed transactions do not require all methods to be associated with transactions. When developing a bean, you can specify which of the bean's methods are associated with transactions by setting the transaction attributes.
Enterprise beans that use container-managed transaction demarcation must not use any transaction management methods that interfere with the container's transaction demarcation boundries. Examples of such methods are the
commit,setAutoCommit, androllbackmethods ofjava.sql.Connectionor thecommitandrollbackmethods ofjavax.jms.Session. If you require control over the transaction dermarkation, you must use application-managed transaction demarcation.Enterprise beans that use container-managed transaction demarcation also must not use the
javax.transaction.UserTransactioninterface.Transaction Attributes
A transaction attribute controls the scope of a transaction. Figure 34-1 illustrates why controlling the scope is important. In the diagram,
method-Abegins a transaction and then invokesmethod-BofBean-2. Whenmethod-Bexecutes, does it run within the scope of the transaction started bymethod-A, or does it execute with a new transaction? The answer depends on the transaction attribute ofmethod-B.
![]()
A transaction attribute can have one of the following values:
Required
If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method.
The
Requiredattribute is the implicit transaction attribute for all enterprise bean methods running with container-managed transaction demarcation. You typically do not set theRequiredattribute unless you need to override another transaction attribute. Because transaction attributes are declarative, you can easily change them later.RequiresNew
If the client is running within a transaction and invokes the enterprise bean's method, the container takes the following steps:
If the client is not associated with a transaction, the container starts a new transaction before running the method.
You should use the
RequiresNewattribute when you want to ensure that the method always runs within a new transaction.Mandatory
If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container throws the
TransactionRequiredException.Use the
Mandatoryattribute if the enterprise bean's method must use the transaction of the client.NotSupported
If the client is running within a transaction and invokes the enterprise bean's method, the container suspends the client's transaction before invoking the method. After the method has completed, the container resumes the client's transaction.
If the client is not associated with a transaction, the container does not start a new transaction before running the method.
Use the
NotSupportedattribute for methods that don't need transactions. Because transactions involve overhead, this attribute may improve performance.Supports
If the client is running within a transaction and invokes the enterprise bean's method, the method executes within the client's transaction. If the client is not associated with a transaction, the container does not start a new transaction before running the method.
Because the transactional behavior of the method may vary, you should use the
Supportsattribute with caution.Never
If the client is running within a transaction and invokes the enterprise bean's method, the container throws a
RemoteException. If the client is not associated with a transaction, the container does not start a new transaction before running the method.Summary of Transaction Attributes
Table 34-1 summarizes the effects of the transaction attributes. Both the T1 and the T2 transactions are controlled by the container. A T1 transaction is associated with the client that calls a method in the enterprise bean. In most cases, the client is another enterprise bean. A T2 transaction is started by the container just before the method executes.
In the last column of Table 34-1, the word None means that the business method does not execute within a transaction controlled by the container. However, the database calls in such a business method might be controlled by the transaction manager of the DBMS.
Setting Transaction Attributes
Transaction attributes are specified by decorating the enterprise bean class or method with a
javax.ejb.TransactionAttributeannotation, and setting it to one of thejavax.ejb.TransactionAttributeTypecontants.If you decorate the enterprise bean class with
@TransactionAttribute, the specifiedTransactionAttributeTypeis applied to all the business methods in the class. Decoration a business method with@TransactionAttributeapplies theTransactionAttributeTypeonly to that method. If a@TransactionAttribute annotation decorates both the class and the method, the methodTransactionAttributeTypeoverrides the classTransactionAttributeType.The
TransactionAttributeTypeconstants encapsulate the transaction attributes described earlier in this section.The following code snippet demonstrates how to use the
@TransactionAttributeannotation:@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
TransactionBeanclass's transaction attribute has been set to NotSupported.firstMethodhas been set to RequiresNew, andsecondMethodhas been set to Required. Because a @TransactionAttribute set on a method overrides the class @TransactionAttribute, calls tofirstMethodwill create a new transaction, and calls tosecondMethodwill either run in the current transaction, or start a new transaction. Calls tothirdMethodorfourthMethoddo 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
setRollbackOnlymethod of theEJBContextinterface, 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 tosetRollbackOnly.Synchronizing a Session Bean's Instance Variables
The
SessionSynchronizationinterface, 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 theSessionSynchronizationmethods--afterBegin,beforeCompletion, andafterCompletion--at each of the main stages of a transaction.The
afterBeginmethod informs the instance that a new transaction has begun. The container invokesafterBeginimmediately before it invokes the business method.The container invokes the
beforeCompletionmethod after the business method has finished, but just before the transaction commits. ThebeforeCompletionmethod is the last opportunity for the session bean to roll back the transaction (by callingsetRollbackOnly).The
afterCompletionmethod indicates that the transaction has completed. It has a singlebooleanparameter whose value istrueif the transaction was committed andfalseif it was rolled back.Methods Not Allowed in Container-Managed Transactions
You should not invoke any method that might interfere with the transaction boundaries set by the container. The list of prohibited methods follows:
You can, however, use these methods to set boundaries in application-managed transactions.