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 commit and rollback methods of the java.sql.Connection interface. The beginning of a transaction is implicit. A transaction begins with the first SQL statement that follows the most recent commit, rollback, or connect statement. (This rule is generally true, but may vary with DBMS vendor.)

Source Code

The source code for the following example is in the j2eetutorial/examples/src/ejb/warehouse directory. To compile the code, go to the j2eetutorial/examples directory and type ant bank. To create the database tables, type ant create-warehouse-table. A sample WarehouseApp.ear file is in the j2eetutorial/examples/ears directory.

The following code is from the WarehouseEJB example, a session bean that uses the Connection interface's methods to delimit bean-managed transactions. The ship method starts by invoking setAutoCommit on the Connection object named con. This invocation tells the DBMS not to automatically commit every SQL statement. Next, the ship method calls routines that update the order_item and inventory database 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 {
      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());
       }
   }
}