JDBC Transactions

Basic Java
≈ 2 min read

By default, each command is committed separately

A new JDBC connection normally works in auto-commit mode: after successful execution, each SQL command immediately becomes its own committed transaction. This is convenient for independent changes, but several related steps can then complete only partially.

Imagine a money transfer: decreasing one account balance and increasing another must be one unit of work. If the first command has already been committed and the second fails, the data is left in an intermediate state.

Disable auto-commit and control the boundary yourself

connection.setAutoCommit(false);

try {
    debit.executeUpdate();
    credit.executeUpdate();

    connection.commit();
} catch (SQLException e) {
    connection.rollback();
    throw e;
}

After setAutoCommit(false), changes are no longer committed automatically after each command. commit() confirms the accumulated changes, while rollback() cancels the changes of the current transaction.

A transaction belongs to a Connection

Commands participate in the same JDBC transaction because they are executed through the same connection. If two related commands are sent through different Connection objects, an ordinary commit() on one of them does not control the other.

Rollback must be part of error handling. If one of the related operations fails after auto-commit has been disabled, you should not simply leave the method and hope the connection state fixes itself.