background image

Container-Managed Transactions

<< What Is a Transaction | RequiresNew Attribute >>
<< What Is a Transaction | RequiresNew Attribute >>

Container-Managed Transactions

step, the transaction would roll back and undo the data modifications made by the debit
statement. Although the transaction fails, data integrity would be intact because the accounts
still balance.
In the preceding pseudocode, the begin and commit statements mark the boundaries of the
transaction. When designing an enterprise bean, you determine how the boundaries are set by
specifying either container-managed or bean-managed transactions.
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
boundaries. Examples of such methods are the commit, setAutoCommit, and rollback methods
of java.sql.Connection or the commit and rollback methods of javax.jms.Session. If you
require control over the transaction demarcation, you must use application-managed
transaction demarcation.
Enterprise beans that use container-managed transaction demarcation also must not use the
javax.transaction.UserTransaction
interface.
Transaction Attributes
A transaction attribute controls the scope of a transaction.
Figure 33­1
illustrates why
controlling the scope is important. In the diagram, method-A begins a transaction and then
invokes method-B of Bean-2. When method-B executes, does it run within the scope of the
transaction started by method-A, or does it execute with a new transaction? The answer depends
on the transaction attribute of method-B.
Container-Managed Transactions
The Java EE 5 Tutorial · September 2007
998