Sun GlassFish Mobility Platform 1.1 Developer's Guide for Enterprise Connectors

Extending the TransactionManager Class

The MusicAlbumProvider.java file includes the implementation of the TransactionManager class. The TransactionManager class can be implemented in a separate file, but the relationships between the two classes mean that it is simpler to keep them together. It is also possible to use the default implementation of the TransactionManager class instead of implementing it yourself.

For details on this class, see The TransactionManager Class.

The MusicDB implementation of this class is called MusicAlbumTransactionManager. This class manages the database transactions for MusicAlbum objects using the JDBC API. It turns the database's auto-commit feature off if it has one and starts, stops, and aborts database transactions. The class definition begins with the constructor, which takes no arguments.

    public class MusicAlbumTransactionManager extends
            TransactionManager<MusicAlbumProvider> {

        public MusicAlbumTransactionManager() {
            super(MusicAlbumProvider.this);
            
            assert (sqlConnection != null);
            try {
                sqlConnection.setAutoCommit(false);
            }
            catch (SQLException e) {
                // Ignore if not supported by DB
            }
        }

The abortTransaction method calls the JDBC Connection.rollback method:

        @Override
        public void abortTransaction() {
            logger.debug("Aborting transaction on SQL connection " 
                    + sqlConnection);
            try {
                sqlConnection.rollback();
            }
            catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

The beginTransaction and endTransaction methods are closely linked. The endTransaction method commits the current transaction, an action that automatically starts the next transaction. The beginTransaction method simply calls endTransaction.

        @Override
        public void beginTransaction() {
            endTransaction();   // starts a new one
        }
        @Override
        public void endTransaction() {
            logger.debug("Starting/Committing transaction on SQL connection " 
                    + sqlConnection);
            try {
                sqlConnection.commit();
            }
            catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }