When a Connection is in a distributed (JTA) transaction, the Connection’s transactional state is controlled by the JTA Transaction Manager and the transactional methods on the Connection cannot be called. When getConnection() is called outside the scope of a distributed transaction, a Connection is returned in local transaction mode. In this mode, the transactional state is controlled directly by the code that is using the Connection. If your code obtains a connection in local transaction mode, make sure that your code calls commit() or rollback() on the Connection when it is obtained.

Here is an example of using a Connection in a distributed transaction:

TransactionDemarcation td = new TransactionDemarcation();
Connection c = null;
try {
  td.begin(getTransactionManager(), td.REQUIRED);
  try {
    c = getDataSource().getConnection();
    // Perform JDBC/SQL work here
    // NOTE: Commit/rollback is not called
  } catch (SQLException sqle) {
    // Log, print, or handle the exception, maybe setting the
    // transaction to be rollback-only.
  } finally {
    try {
      if (c != null)
        c.close();
    } catch (SQLException sqle2) {
      // Log, print, or handle the exception
    } finally {
      td.end();
    }
  }
} catch (TransactionDemarcationException tde) {
  // Log, print, or handle the exception
}

Here is an example of using a Connection in local transaction mode:

Connection c = null;
try {
  c = getDataSource().getConnection();
  // Perform JDBC/SQL work here
  c.commit();
} catch (SQLException sqle) {
  // Log, print, or handle the exception
  try {
    c.rollback();
  } catch (SQLException sqle2) {
    // Log, print, or handle the exception
  }
} finally {
  try {
    if (c != null)
      c.close();
  } catch (SQLException sqle) {
    // Log, print, or handle the exception
  }
}

Note that in the distributed transaction example, commit() and rollback() are not called, but in the local transaction example, they are called.

Local transaction mode allows the use of JDBC’s auto-commit mode with the Connection. When auto-commit is enabled, each SQL statement is treated as a transaction and is committed automatically right after the statement is completed. When auto-commit is disabled, your application is responsible for calling commit() or rollback() on the connection.

 
loading table of contents...