15 - Bean-Managed Transactions

Bean-Managed Transactions

In the bean managed transactions, instead of leaving the transaction boundaries handling to the container, the coder marks the transaction boundaries using the JTA method: begin, commit, and rollback of the interface UserTransaction or the standard setAutoCommit(false), commit, rollback operations of the JDBC connection interface.

JTA Transactions

The Java Transaction API provides  standard and independent interfaces that can be used to handle the transaction boundaries away from the transaction managed specific implementation. It provides the interface UserTransaction that contains 3 methods - begin, commit and rollback.

JTA can handle transactions running on multiple databases independently from the vendor specific implementations of each database. JDBC transactions may not succeed with such situations.

package com.ejb3.webservice;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.transaction.UserTransaction;

@Stateless
@LocalBean
@TransactionManagement(TransactionManagementType.BEAN)
public class BeanManagedTransactionExample {

     @Resource
    UserTransaction ut;

    public void doAction() {
        try {
            ut.begin();
            insertNewElement();
            updateAnotherElement();
            logAction();
            ut.commit();
            sendInsertUpdateNotification();
        } catch (Exception e) {
            try {
                ut.rollback();
            } catch (Exception ex) {
                // Failed to rollback the transaction
            }
        }
    }
}

As noted, the check before commit doesn’t exist in bean managed transactions as the coder can control when to commit the transaction.

Another note is that you are allowed to return the method without calling the commit method, but this is valid only for the Statefull beans as the container retains the transaction across multiple client calls even if the methods open and close database connections. This is handled by attaching the transaction to the bean instead of attaching it to the database connection object, and for sure, such behavior cannot be achieved using JDBC transaction management interfaces.

Like us on Facebook