|
Download
FAQ History |
|
API
Search Feedback |
Bean-Managed Transactions
In a bean-managed transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. 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 will make coding your bean difficult, you should consider using bean-managed transactions.
The following pseudocode illustrates the kind of fine-grained control you can obtain with bean-managed transactions. By checking various conditions, the pseudocode decides whether to start or stop different transactions within the business method.
begin transaction ... update table-a ... if (condition-x) commit transaction else if (condition-y) update table-b commit transaction else rollback transaction begin transaction update table-c commit transactionWhen coding a bean-managed transaction for session or message-driven beans, you must decide whether to use JDBC or JTA transactions. The sections that follow discuss both types of transactions.
JDBC Transactions
A JDBC transaction is controlled by the transaction manager of the DBMS. You may want to use JDBC transactions when wrapping legacy code inside a session bean. To code a JDBC transaction, you invoke the
commitandrollbackmethods of thejava.sql.Connectioninterface. The beginning of a transaction is implicit. A transaction begins with the first SQL statement that follows the most recentcommit,rollback, orconnectstatement. (This rule is generally true but may vary with DBMS vendor.)The source code for the following example is in the
<INSTALL>/j2eetutorial14/examples/ejb/warehouse/directory.The following code is from the
WarehouseBeanexample, a session bean that uses theConnectioninterface's methods to delimit bean-managed transactions. Theshipmethod starts by invokingsetAutoCommiton theConnectionobject namedcon. This invocation tells the DBMS not to automatically commit every SQL statement. Next, theshipmethod calls routines that update theorder_itemandinventorydatabase tables. If the updates succeed, the transaction is committed. If an exception is thrown, however, the transaction is rolled back.public void ship (String productId, String orderId, int quantity) { try { makeConnection(); con.setAutoCommit(false); updateOrderItem(productId, orderId); updateInventory(productId, quantity); con.commit(); } catch (Exception ex) { try { con.rollback(); throw new EJBException("Transaction failed: " + ex.getMessage()); } catch (SQLException sqx) { throw new EJBException("Rollback failed: " + sqx.getMessage()); } } finally { releaseConnection(); } }Deploying and Running the WarehouseBean Example
WarehouseBeanis a session bean that uses bean-managed, JDBC transactions. These steps assume that you are familiar with the steps needed to create and deploy an enterprise application usingdeploytool, as described in Chapter 25. To deploy and run the example, do the following.Compiling the WarehouseBean Example
To compile the classes and interfaces in the
WarehouseBeanexample, follow these steps:
- In a terminal window, go to this directory:
<INSTALL>/j2eetutorial14/examples/ejb/warehouse/- Start the PointBase server. For instructions, see Starting and Stopping the PointBase Database Server.
- Create the database tables and data by typing
asant create-db_common- Type the following command to build the enterprise bean's classes and interfaces:
asant buildPackaging the WarehouseBean Example
The
WarehouseBeansession bean uses bean-managed transactions. These steps assume that you are familiar with the steps needed to create and deploy an enterprise application usingdeploytool, as described in Chapter 24.Creating the J2EE Application
Create a new application named
WarehouseAppin:Packaging the Enterprise Bean
Packaging the Application Client
Specifying the Application Client's Enterprise Bean Reference
When it invokes the
lookupmethod,WarehouseClientrefers to the home of an enterprise bean:You specify this reference as follows:
- In the tree, select
WarehouseClient.- Select the EJB Ref's tab.
- Click Add.
- In the Coded Name field, enter
ejb/SimpleWarehouse.- In the EJB Type field, select
Session.- In the Interfaces field, select
Remote.- In the Home Interface field, enter
WarehouseHome.- In the Local/Remote Interface field, enter
Warehouse.- Click OK.
- Select the line you just added.
- Under Sun-specific Settings for
ejb/SimpleWarehouse, select JNDI Name.- In the JNDI Name field, select
WarehouseBean.- Select File
Save.
Deploying the J2EE Application
- Select
WarehouseAppindeploytool.- Select Tools
Deploy.
- Under Connection Settings, enter the user name and password for the J2EE application server.
- Tell
deploytoolto create a JAR file that contains the client stubs:- Click OK.
- In the Distribute Module dialog box, click Close when the deployment completes successfully.
Running the Application Client
In the terminal window, the client displays these lines:
JTA Transactions
JTA is the abbreviation for the Java Transaction API. This API allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE Application Server implements the transaction manager with the Java Transaction Service (JTS). But your code doesn't call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines.
A JTA transaction is controlled by the J2EE transaction manager. You may want to use a JTA transaction because it can span updates to multiple databases from different vendors. A particular DBMS's transaction manager may not work with heterogeneous databases. However, the J2EE transaction manager does have one limitation: it does not support nested transactions. In other words, it cannot start a transaction for an instance until the preceding transaction has ended.
The source code for the following example is in the
<INSTALL>/j2eetutorial14/examples/ejb/teller/directory.To demarcate a JTA transaction, you invoke the
begin,commit, androllbackmethods of thejavax.transaction.UserTransactioninterface. The following code, taken from theTellerBeanclass, demonstrates theUserTransactionmethods. Thebeginandcommitinvocations delimit the updates to the database. If the updates fail, the code invokes therollbackmethod and throws anEJBException.public void withdrawCash(double amount) { UserTransaction ut = context.getUserTransaction(); try { ut.begin(); updateChecking(amount); machineBalance -= amount; insertMachine(machineBalance); ut.commit(); } catch (Exception ex) { try { ut.rollback(); } catch (SystemException syex) { throw new EJBException ("Rollback failed: " + syex.getMessage()); } throw new EJBException ("Transaction failed: " + ex.getMessage()); } }Deploying and Running the TellerBean Example
The
TellerBeansession bean uses bean-managed JTA transactions. These steps assume that you are familiar with the steps needed to create and deploy an enterprise application usingdeploytool, as described in Chapter 25. To deploy and run theTellerBeanexample, perform these steps.Compiling the TellerBean Example
To compile the classes and interfaces in the
TellerBeanexample, follow these steps:
- In a terminal window, go to this directory:
<INSTALL>/j2eetutorial14/examples/ejb/teller/- Start the PointBase server. For instructions, see Starting and Stopping the PointBase Database Server.
- Create the database tables and data by typing
asant create-db_common- Type the following command to build the enterprise bean's classes and interfaces:
asant buildPackaging the TellerBean Example
The
TellerBeansession bean uses JTA transactions. These steps assume that you are familiar with the steps needed to create and deploy an enterprise application usingdeploytool, as described in Chapter 24.Creating the J2EE Application
Create a new application named
TellerAppin
<INSTALL>/j2eetutorial14/examples/ejb/teller/Packaging the Enterprise Bean
- Create a new enterprise bean in
TellerAppby selecting FileNew
Enterprise Bean.
- In the EJB JAR screen:
- In the General screen:
- In the Configuration Options screen, select No under Expose Bean as Web Service End Point.
- Click Finish.
- Select
TellerBeanindeploytool's tree.- In the Transactions tab select Bean-Managed under Transaction Management.
- In the Resource Ref's tab:
Packaging the Application Client
Specifying the Application Client's Enterprise Bean Reference
When it invokes the
lookupmethod,TellerClientrefers to the home of an enterprise bean:You specify this reference as follows:
- In the tree, select
TellerClient.- Select the EJB Ref's tab.
- Click Add.
- In the Coded Name field, enter
ejb/SimpleTeller.- In the EJB Type field, select
Session.- In the Interfaces field, select
Remote.- In the Home Interface field, enter
TellerHome.- In the Local/Remote Interface field, enter
Teller.- Click OK.
- Select the line you just added.
- Under Sun-specific Settings for
ejb/SimpleTeller, select JNDI Name.- In the JNDI Name field, select
TellerBean.- Select File
Save.
Deploying the J2EE Application
- Select
TellerAppindeploytool.- Select Tools
Deploy.
- Under Connection Settings, enter the user name and password for the J2EE application server.
- Tell
deploytoolto create a JAR file that contains the client stubs:- Click OK.
- In the Distribute Module dialog box, click Close when the deployment completes successfully.
Running the Application Client
In the terminal window, the client displays these lines:
Returning without Committing
In a stateless session bean with bean-managed transactions, a business method must commit or roll back a transaction before returning. However, a stateful session bean does not have this restriction.
In a stateful session bean with a JTA transaction, the association between the bean instance and the transaction is retained across multiple client calls. Even if each business method called by the client opens and closes the database connection, the association is retained until the instance completes the transaction.
In a stateful session bean with a JDBC transaction, the JDBC connection retains the association between the bean instance and the transaction across multiple calls. If the connection is closed, the association is not retained.
Methods Not Allowed in Bean-Managed Transactions
Do not invoke the
getRollbackOnlyandsetRollbackOnlymethods of theEJBContextinterface in bean-managed transactions. These methods should be used only in container-managed transactions. For bean-managed transactions, invoke thegetStatusandrollbackmethods of theUserTransactioninterface.
|
Download
FAQ History |
|
API
Search Feedback |
All of the material in The J2EE(TM) 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.