Java Reference
In-Depth Information
<enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>YachtSessionEJB</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
The asterisk (*) between the method-name tags indicates all methods. This listing specifies the
transaction attribute for all methods as Required . For finer granularity, you can assign each method a
different transaction attribute.
Bean-Managed Transaction
In a bean-managed transaction , the code explicitly marks the boundaries of the transaction. Note that
only session or message-driven beans can use bean-managed transactions. An entity bean cannot
have bean-managed transactions; it must use container-managed transactions instead. Although beans
with container-managed transactions require less coding, they have one limitation: when a method is
executing, it can be associated with either a single transaction or no transaction at all. If this limitation
makes coding your bean difficult, you should consider using bean-managed transactions. For example,
if multiple databases are accessed and a two-phase commit is required, a bean-managed transaction
should be used.
Note
Entity beans must use container-managed transactions. Session beans and message-
driven beans can use either container-managed transactions or bean-managed
transactions.
When coding a bean-managed transaction for session or message-driven beans, the bean developer
must decide whether to use Java Database Connectivity (JDBC) or Java Transaction Architecture (JTA)
transactions. The JDBC transaction has been discussed intensively in previous chapters and is not
repeated here. However, using JDBC transactions is not recommended in EJB development. JDBC
transactions are usually only used when wrapping legacy code inside a session bean.
In many enterprise applications, the client needs to combine the invocation of multiple methods into a
single transaction. The methods can be on the same EJB, or they can be on multiple EJBs. To
demarcate transactions across multiple method invocations, it is recommended that you use the JTA
APIs. Actually, only one interface in the JTA APIs, javax.transaction.UserTransaction , needs
to be used to demarcate a JTA transaction. This interface has a few useful methods, such as begin ,
commit , and rollback . A bean method may look like this:
public void withdrawCash(double amount) {
UserTransaction ut = context.getUserTransaction();
try {
// Start transaction
ut.begin();
// perform tasks
updateChecking(amount);
machineBalance -= amount;
insertMachine(machineBalance);
Search WWH ::




Custom Search