3.3.  Use JDBC transactions


A transaction is a logical unit of work.

Transactional support allows applications to ensure the following:

Transactions are used to provide data integrity, correct application semantics, and a consistent view of data during concurrent access. All Java Database Connectivity (JDBC) compliant drivers must support transactions.

All transactional work is handled at the Connection object level. When the work for a transaction completes, it can be finalized by calling the commit() method. If the application aborts the transaction, the rollback() method is called.

All Statement objects under a Connection are a part of the transaction. This means is that if an application creates three Statement objects and uses each object to make changes to the database, when a commit or rollback call happens, the work for all three statements either becomes permanent or is discarded.

JDBC auto-commit mode

By default, JDBC uses an operation mode called auto-commit. This means that every update to the database is immediately made permanent.

Any situation where a logical unit of work requires more than one update to the database cannot be done safely in auto-commit mode. If something happens to the application or the system after one update is made and before any other updates are made, the first change cannot be undone when running in auto-commit mode.

Because changes are instantly made permanent in auto-commit mode, there is no need for the application to call the commit() method or the rollback() method. This makes applications easier to write.

Auto-commit mode can be enabled and disabled dynamically during a connection's existence. Auto-commit can be disabled in the following way, assuming that data source already exists:

Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);  // Disables auto-commit

NOTE: If the auto-commit setting is changed in the middle of a transaction, any pending work is automatically committed. If setAutoCommit(...) is called and the auto-commit mode is not changed, the call is a no-op.

NOTE: there is NO Connection.begin() method to begin a transaction!

The first call of Connection.setAutoCommit(false) and each call of Connection.commit() implicitly mark the start of a transaction. Transactions can be undone before they are committed by calling Connection.rollback().

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide