With container-managed transaction beans, you are limited to a single transaction per method. You would like to group some important sections of code into a single method but use multiple transactions within the entire method. You need transaction control like this if you have a method that contains critical sections of code that cannot be broken into separate methods for CMT control. This enables you to roll back a small section of code and exit the method without executing the remaining method. This applies only to session beans, because entity beans must always use container-managed transactions.

In order to enable custom transactions it is necessary change session bean to manage its own transactions by altering its XML descriptor, like in the sample below:

...
<session>
  <ejb-name>SomeSession</ejb-name>
  <home>SomeSessionHome</home>
  <remote>SomeSession</remote>
  <ejb-class>SomeSessionBean</ejb-class>

  <session-type>Stateful</session-type>

  <!-- enable bean-managed transactions: -->
  <transaction-type>Bean</transaction-type>
</session>
...

Here is bean method:

public void someMethod() {

  UserTransaction transaction = null;

  // the first transaction:
  try {
    transaction = ejbContext.getUserTransaction();
    transaction.begin();

    // perform code...

    transaction.commit();
  catch (Exception e) {
    //need to rollback?
    if (transaction != null) {
      transaction.rollback();
    }
  }

  // the second transaction:
  try {
    transaction = ejbContext.getUserTransaction();
    transaction.begin();

    // perform code...

    transaction.commit();
  catch (Exception e) {
    //need to rollback?
    if (transaction != null) {
      transaction.rollback();
    }
  }

  // and so on ...
}