Transactions and rollback
What you will learn
A transaction combines database changes into one commit or rollback decision. A small reservation must decrease stock and insert a reservation together, never as independent auto-committed updates.
- Choose a single transaction-owning connection.
- Preserve primary and rollback exceptions.
- Interpret SQLState without assuming all failures are retryable.
Prerequisite: Java exceptions, interfaces, Optional and testing fundamentals. Database execution is NOT RUN; local JDK-only examples and test doubles are checked separately.
Transaction boundary helper
import java.sql.Connection;import java.sql.SQLException;
public final class Tx { private Tx() {} @FunctionalInterface public interface Work { void run() throws SQLException; }
// Requires a freshly borrowed connection in auto-commit mode. // Caller closes it; do not reuse it after a failed rollback. public static void run(Connection c, Work work) throws SQLException { if (!c.getAutoCommit()) throw new SQLException("transaction already active or configured"); c.setAutoCommit(false); try { work.run(); c.commit(); } catch (SQLException | RuntimeException | Error failure) { try { c.rollback(); } catch (SQLException rollbackFailure) { failure.addSuppressed(rollbackFailure); } throw failure; } // No setAutoCommit(true) on failure: it could commit unfinished work. // The owning caller must close; a pool must reset/discard appropriately. }}Compiled; call order is locally tested by Probe. No actual commit or rollback occurs.
Transaction ownership
A fresh JDBC connection defaults to auto-commit, with completion of each statement defining its commit boundary. Disable auto-commit before related statements and commit only after all checks succeed. Use the same connection for the entire unit of work. Explicitly commit or rollback before close; behavior of closing an active transaction is implementation-defined. Changing auto-commit mode during an active transaction commits it, so do not restore true after a failed rollback.
Failures and uncertainty
If work or commit throws, attempt rollback and keep the original failure; attach a rollback exception as suppressed. The caller closes the connection and must follow pool discard/reset rules. If commit fails due to communication loss, the outcome may be unknown even after rollback attempt. Do not blindly retry; reconcile using an application-level idempotency design. This helper rejects a connection already configured with auto-commit false rather than owning someone else’s transaction.
Isolation and SQLState
A guarded stock decrement includes stock >= quantity in the UPDATE predicate and requires one affected row. It reduces a read-then-write race for this database design but is not a tested concurrency guarantee here. PostgreSQL 17 codes 23505 and 23514 denote unique and check constraint violations respectively; other failures must remain distinguishable. Use SQLState and chained exceptions for diagnosis, avoid exposing raw sensitive messages, and test actual rollback from a fresh connection.
Synthetic SQLState classification
import java.sql.SQLException;
public class Main { static String classify(SQLException e) { if ("23505".equals(e.getSQLState())) return "duplicate"; if ("23514".equals(e.getSQLState())) return "check violation"; return "unclassified"; } public static void main(String[] args) { System.out.println(classify(new SQLException("synthetic", "23505"))); System.out.println(classify(new SQLException("synthetic", "23514"))); System.out.println(classify(new SQLException("synthetic"))); }}Locally executed: duplicate, check violation, unclassified on separate lines. No server error was generated.
Verify transaction call ordering
import java.lang.reflect.Proxy;import java.sql.*;import java.util.*;
public class Probe { static Connection connection(List<String> events, boolean failCommit, boolean failRollback, boolean autoCommit) { return (Connection) Proxy.newProxyInstance(Probe.class.getClassLoader(), new Class<?>[]{Connection.class}, (proxy, method, args) -> { String name = method.getName(); events.add(name + (name.equals("setAutoCommit") ? ":" + args[0] : "")); return switch (name) { case "getAutoCommit" -> autoCommit; case "setAutoCommit", "close" -> null; case "commit" -> { if (failCommit) throw new SQLException("commit failed"); yield null; } case "rollback" -> { if (failRollback) throw new SQLException("rollback failed"); yield null; } default -> throw new UnsupportedOperationException(name); }; }); } static void check(boolean b) { if (!b) throw new AssertionError("contract violated"); } public static void main(String[] args) throws Exception { List<String> events = new ArrayList<>(); try (Connection c = connection(events, false, false, true)) { Tx.run(c, () -> events.add("work")); } check(events.equals(List.of("getAutoCommit", "setAutoCommit:false", "work", "commit", "close"))); System.out.println("commit order passed"); events.clear(); SQLException original = new SQLException("work failed"); try (Connection c = connection(events, false, true, true)) { Tx.run(c, () -> { events.add("work"); throw original; }); throw new AssertionError("expected failure"); } catch (SQLException e) { check(e == original && e.getSuppressed().length == 1); } check(events.equals(List.of("getAutoCommit", "setAutoCommit:false", "work", "rollback", "close"))); System.out.println("rollback and suppression passed"); events.clear(); try (Connection c = connection(events, true, false, true)) { Tx.run(c, () -> events.add("work")); throw new AssertionError("expected commit failure"); } catch (SQLException e) { check(e.getMessage().equals("commit failed")); } check(events.equals(List.of("getAutoCommit", "setAutoCommit:false", "work", "commit", "rollback", "close"))); System.out.println("commit failure order passed"); events.clear(); try (Connection c = connection(events, false, false, false)) { Tx.run(c, () -> { throw new AssertionError("must not run"); }); throw new AssertionError("expected rejection"); } catch (SQLException e) { check(e.getMessage().contains("already active")); } check(events.equals(List.of("getAutoCommit", "close"))); System.out.println("existing transaction rejection passed"); }}Locally executed with a dynamic proxy implementing selected Connection methods. Four checks: success, rollback failure suppression, commit failure, rejection of existing transaction. This is not a database or pool simulator.
Common mistakes
Do not use separate connections for related changes, call setAutoCommit(true) to recover from failed rollback, swallow errors, or claim a test double proves durable rollback.
Practice
A stock update succeeds but inserting the reservation fails. Trace the expected JDBC calls and explain what a database integration test must observe.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: connection · exception · states.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transactions and rollback — knowledge check
JDBC knowledge check.
Which connection should both writes use?
When should commit be called?
What can setAutoCommit(true) do during an active transaction?
How should a rollback failure be retained?
What does PostgreSQL SQLState 23505 mean?