Concept Explanation
A bank transfer is two operations: subtract from account A, add to account B. If the program crashes between them, money vanishes. A transaction groups operations so that either all succeed or none do.
By default JDBC runs in auto-commit mode — every statement commits immediately, which is exactly what you do not want here.
The Pattern
Connection conn = dataSource.getConnection();
try {
conn.setAutoCommit(false); // begin transaction
try (PreparedStatement debit = conn.prepareStatement(
"UPDATE accounts SET balance = balance - ? WHERE id = ?")) {
debit.setBigDecimal(1, amount);
debit.setLong(2, fromId);
debit.executeUpdate();
}
try (PreparedStatement credit = conn.prepareStatement(
"UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
credit.setBigDecimal(1, amount);
credit.setLong(2, toId);
credit.executeUpdate();
}
conn.commit(); // both succeeded
} catch (SQLException e) {
conn.rollback(); // undo everything
throw e;
} finally {
conn.setAutoCommit(true); // restore before returning to pool
conn.close();
}
ACID, Briefly
- Atomicity — all or nothing.
- Consistency — constraints hold before and after.
- Isolation — concurrent transactions do not see each other's half-finished work.
- Durability — once committed, a crash cannot lose it.
Isolation Levels
| Level | Prevents |
|---|---|
READ_UNCOMMITTED | nothing (can read uncommitted "dirty" data) |
READ_COMMITTED | dirty reads — the common default |
REPEATABLE_READ | dirty + non-repeatable reads |
SERIALIZABLE | everything, at the cost of concurrency |
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
Savepoints
For partial rollback inside a long transaction:
Savepoint sp = conn.setSavepoint("afterDebit");
// ... more work ...
conn.rollback(sp); // undo back to the savepoint only
Common Mistakes
- Forgetting
setAutoCommit(false): Each statement commits on its own androllback()does nothing. - No rollback in catch: The transaction stays open, holding locks until it times out.
- Leaving auto-commit off on a pooled connection: The next borrower inherits your broken state. Always restore it.
- Transactions that span user input: Never hold a transaction open while waiting for a human.
Best Practices
- Keep them short: Long transactions hold locks and block other work.
- Use the weakest sufficient isolation:
SERIALIZABLEeverywhere will throttle your app. - In Spring, prefer
@Transactionalover manual commit/rollback — far less to get wrong.
Practice Exercises
- The Transfer: Implement the bank transfer above, then throw a deliberate exception between the two updates and confirm no money moved.
- The Savepoint: Insert three rows inside one transaction, set a savepoint after the second, then roll back to it and verify only two remain.
- The Dirty Read: With two connections, set one to
READ_UNCOMMITTEDand observe it reading the other's uncommitted change.