At times, you might need to demarcate transactions in your code. Generally, you should use programmatic demarcation as little as possible, as it is error-prone and can interfere with the application server’s own transaction demarcation mechanisms. If you find it necessary to use programmatic demarcation, you must be very careful to ensure that your code handles any unexpected errors and conditions.

The Oracle ATG Web Commerce platform includes two classes that you can use to demarcate transactions in code:

Using the UserTransactionDemarcation Class

The following example illustrates how to use the UserTransactionDemarcation class:

UserTransactionDemarcation td = new UserTransactionDemarcation ();
try {
  try {
    td.begin ();

    ... do transactional work ...
  }
  finally {
    td.end ();
  }
}
catch (TransactionDemarcationException exc) {
  ... handle the exception ...
}

There are a few things to note about using the UserTransactionDemarcation class:

Using the TransactionDemarcation Class

The following example illustrates using the TransactionDemarcation class:

TransactionManager tm = ...
TransactionDemarcation td = new TransactionDemarcation ();
try {
  try {
    td.begin (tm, td.REQUIRED);

    ... do transactional work ...
  }
  finally {
    td.end ();
  }
}
catch (TransactionDemarcationException exc) {
  ... handle the exception ...
}

There are a few things to note about using the TransactionDemarcation class:

The TransactionDemarcation class takes care of both creating and ending transactions. For example, if the TransactionDemarcation object is used with a RequiresNew transaction mode, the end() call commits or rolls back the transaction created by the begin() call. The application is not expected to commit or rollback the transaction itself.

If for some reason the application needs to force the transaction to end, this can be done by calling the TransactionManager.commit() method:

TransactionManager tm = ...
TransactionDemarcation td = new TransactionDemarcation ();
try {
  try {
    td.begin (tm);

    ... do transactional work ...

    tm.commit ();
  }
  catch (RollbackException exc) { ... }
  catch (HeuristicMixedException exc) { ... }
  catch (HeuristicRollbackException exc) { ... }
  catch (SystemException exc) { ... }
  catch (SecurityException exc) { ... }
  catch (IllegalStateException exc) { ... }
  finally {
    td.end ();
  }
}
catch (TransactionDemarcationException exc) {
  ... handle the exception ...
}

Ending a transaction in this way should be avoided wherever possible, because handling all exceptions introduces a lot of complexity in the code. The same result can usually be accomplished by more standard means.