Video in progress

What is autocommit mode in JDBC, and when do you turn it off?

With autocommit on, every SQL statement is its own transaction and is committed immediately. When several statements must succeed or fail together, you turn autocommit off and call commit or rollback yourself.

📖 Answer

In JDBC a new Connection has autoCommit = true by default. If an error occurs between two UPDATEs, the first one has already been saved.

try (Connection con = dataSource.getConnection()) {
    con.setAutoCommit(false);
    try (PreparedStatement debit = con.prepareStatement(
             "UPDATE accounts SET balance = balance - ? WHERE id = ?");
         PreparedStatement credit = con.prepareStatement(
             "UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
        debit.setBigDecimal(1, amount);  debit.setLong(2, fromId);  debit.executeUpdate();
        credit.setBigDecimal(1, amount); credit.setLong(2, toId);   credit.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        con.rollback();   // both are undone
        throw e;
    }
}

With Spring, @Transactional does this for you: it turns autocommit off on the connection taken from the pool and commits when the method finishes.

One subtle point: when the pool takes a connection back, it restores the autocommit state (HikariCP does), but in hand-written code, closing a connection without commit/rollback means the end of the transaction is undefined.