JDBC Transactions, Savepoints & Batch Operations

A transaction makes several SQL statements succeed or fail together, and decides what concurrent transactions can see of each other. JDBC connections start in auto-commit mode, where every statement is its own transaction, which is exactly wrong for multi-step changes such as a money transfer. This page explains how transactions work, then runs commits, rollbacks, isolation levels, lost updates and batch inserts on H2.

Share

Contents

How transactions work

A transaction groups statements so that the database treats them as one unit. The usual summary is ACID: all or nothing (atomicity), constraints hold afterwards (consistency), concurrent transactions do not see each other's half-done work (isolation), and committed changes survive a crash (durability). Databases implement this with a log of changes, which lets them undo an uncommitted transaction and replay committed ones after a crash, and with either row locks or multi-version concurrency control (MVCC), where readers see an older committed version of a row while a writer changes it. H2's default MVStore engine, like PostgreSQL and Oracle, uses MVCC.

In JDBC, a transaction belongs to a Connection. There is no "begin" call: with auto-commit off, a transaction starts with the first statement and ends with commit() or rollback().

The JDBC transaction and batch API
MethodSincePurpose
setAutoCommit(false)JDBC 1Group the following statements into one transaction
commit(), rollback()JDBC 1End the transaction, keeping or discarding its changes
setTransactionIsolation(level)JDBC 1Choose what the transaction sees of others
addBatch(), executeBatch()JDBC 2.0Send many statements in one call
setSavepoint(), rollback(savepoint)JDBC 3.0 (Java 1.4)Undo part of a transaction
executeLargeBatch()JDBC 4.2 (Java 8)Batch with long update counts

All programs run on JDK 21 against H2 2.3.232. Several open two connections to the same in-memory database, which stands in for two users or two threads.

Auto-commit versus a transaction

A transfer is two updates: credit one account, debit the other. The account table has a CHECK (balance >= 0) constraint, and the program tries to move 150 from Ana, who has only 100, so the second update must fail. It runs the same transfer once in auto-commit mode and once in a transaction, then tries a valid transfer and a savepoint.

Java
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;

public class Transfers {

    static void setup(Connection c) throws SQLException {
        try (Statement st = c.createStatement()) {
            st.execute("CREATE TABLE account (id VARCHAR(10) PRIMARY KEY, "
                    + "balance DECIMAL(10,2) CHECK (balance >= 0))");
            st.execute("INSERT INTO account VALUES ('ana', 100.00), ('ben', 50.00)");
        }
    }

    static void move(Connection c, String from, String to, String amount) throws SQLException {
        try (PreparedStatement credit = c.prepareStatement(
                     "UPDATE account SET balance = balance + ? WHERE id = ?");
             PreparedStatement debit = c.prepareStatement(
                     "UPDATE account SET balance = balance - ? WHERE id = ?")) {
            credit.setBigDecimal(1, new BigDecimal(amount));
            credit.setString(2, to);
            credit.executeUpdate();                     // runs first and succeeds
            debit.setBigDecimal(1, new BigDecimal(amount));
            debit.setString(2, from);
            debit.executeUpdate();                      // may violate the CHECK constraint
        }
    }

    static String balances(Connection c) throws SQLException {
        StringBuilder sb = new StringBuilder();
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT id, balance FROM account ORDER BY id")) {
            while (rs.next()) {
                sb.append(rs.getString(1)).append('=').append(rs.getBigDecimal(2)).append(' ');
            }
        }
        return sb.toString().trim();
    }

    public static void main(String[] args) throws Exception {
        // Auto-commit (the default): each statement is committed on its own
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:auto", "sa", "")) {
            setup(c);
            try {
                move(c, "ana", "ben", "150.00");        // ana only has 100
            } catch (SQLException e) {
                System.out.println("auto-commit, failed transfer: SQLState " + e.getSQLState());
            }
            System.out.println("  balances: " + balances(c) + "   <- ben was credited anyway");
        }

        // One transaction: both updates commit together or not at all
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:tx", "sa", "")) {
            setup(c);
            c.setAutoCommit(false);
            try {
                move(c, "ana", "ben", "150.00");
                c.commit();
            } catch (SQLException e) {
                c.rollback();
                System.out.println("transaction, failed transfer: rolled back");
            }
            System.out.println("  balances: " + balances(c));

            move(c, "ana", "ben", "30.00");
            c.commit();
            System.out.println("transaction, valid transfer: " + balances(c));

            // A savepoint undoes part of a transaction
            move(c, "ben", "ana", "10.00");
            Savepoint sp = c.setSavepoint("after_first");
            move(c, "ben", "ana", "20.00");
            c.rollback(sp);
            c.commit();
            System.out.println("two moves, second rolled back to savepoint: " + balances(c));
        }
    }
}

Output:

Output
auto-commit, failed transfer: SQLState 23513
  balances: ana=100.00 ben=200.00   <- ben was credited anyway
transaction, failed transfer: rolled back
  balances: ana=100.00 ben=50.00
transaction, valid transfer: ana=70.00 ben=80.00
two moves, second rolled back to savepoint: ana=80.00 ben=70.00
  1. In auto-commit mode, the credit was committed the moment it ran. The debit then failed on the constraint (SQLState 23513), leaving Ben with 200 and Ana still with 100: 150 was created out of nothing.
  2. With setAutoCommit(false), both updates belong to one transaction. On failure, rollback() undid the credit, and the balances stayed 100 and 50.
  3. The valid transfer of 30 committed both changes together.
  4. A Savepoint marks a point inside a transaction. After moving 10 and then 20 from Ben, rolling back to the savepoint undid only the second move, and the commit kept the first, leaving Ana with 80 and Ben with 70.

A safe transaction template, and when transactions end by themselves

The pattern for any multi-statement change is always the same, so it belongs in one helper. The program wraps it in inTransaction, then checks four situations where a transaction ends without an explicit commit() or rollback(), each of which can surprise you.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TxBehavior {

    static final String URL = "jdbc:h2:mem:txb;DB_CLOSE_DELAY=-1";

    interface Work {
        void run(Connection c) throws SQLException;
    }

    // The standard pattern: commit at the end, roll back on any failure, restore auto-commit
    static void inTransaction(Connection c, Work work) throws SQLException {
        boolean oldAutoCommit = c.getAutoCommit();
        c.setAutoCommit(false);
        try {
            work.run(c);
            c.commit();
        } catch (SQLException | RuntimeException e) {
            c.rollback();
            throw e;
        } finally {
            c.setAutoCommit(oldAutoCommit);
        }
    }

    static int rows() throws SQLException {
        try (Connection c = DriverManager.getConnection(URL, "sa", "");
             Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM log")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    static void insert(Connection c, String msg) throws SQLException {
        try (Statement st = c.createStatement()) {
            st.executeUpdate("INSERT INTO log VALUES ('" + msg + "')");
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection(URL, "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE log (msg VARCHAR(20))");
        }

        try (Connection c = DriverManager.getConnection(URL, "sa", "")) {
            inTransaction(c, conn -> {
                insert(conn, "one");
                insert(conn, "two");
            });
            System.out.println("template, success:      rows=" + rows() + ", autoCommit back to "
                    + c.getAutoCommit());
            try {
                inTransaction(c, conn -> {
                    insert(conn, "three");
                    throw new IllegalStateException("validation failed");
                });
            } catch (IllegalStateException e) {
                System.out.println("template, exception:    rows=" + rows() + " (" + e.getMessage()
                        + ", rolled back)");
            }
        }

        // Uncommitted work is invisible to other connections, and lost when closing
        try (Connection c = DriverManager.getConnection(URL, "sa", "")) {
            c.setAutoCommit(false);
            insert(c, "pending");
            System.out.println("before commit:          other connection sees rows=" + rows());
        }
        System.out.println("closed without commit:  rows=" + rows());

        // In H2, a DDL statement commits the open transaction
        try (Connection c = DriverManager.getConnection(URL, "sa", "")) {
            c.setAutoCommit(false);
            insert(c, "before-ddl");
            try (Statement st = c.createStatement()) {
                st.execute("CREATE TABLE other (x INT)");
            }
            c.rollback();
            System.out.println("rollback after DDL:     rows=" + rows());
        }

        // Turning auto-commit back on commits the open transaction
        try (Connection c = DriverManager.getConnection(URL, "sa", "")) {
            c.setAutoCommit(false);
            insert(c, "switch");
            c.setAutoCommit(true);
            System.out.println("setAutoCommit(true):    rows=" + rows());
        }
    }
}

Output:

Output
template, success:      rows=2, autoCommit back to true
template, exception:    rows=2 (validation failed, rolled back)
before commit:          other connection sees rows=2
closed without commit:  rows=2
rollback after DDL:     rows=3
setAutoCommit(true):    rows=4
  • The template commits when the work succeeds, rolls back on any SQLException or RuntimeException, and restores the previous auto-commit setting in finally. The failed work's row "three" was rolled back, so 2 rows remained. Restoring auto-commit matters with a connection pool, because the next user of the connection expects the default; HikariCP also resets it on return.
  • A second connection saw only the 2 committed rows while "pending" was uncommitted. Closing the connection without a commit discarded the row in H2. The Connection.close documentation leaves this case implementation-defined, so always end transactions explicitly.
  • In H2, a CREATE TABLE inside the transaction committed the pending insert, and the later rollback() had nothing to undo: rows went from 2 to 3. MySQL and Oracle also commit implicitly on DDL; PostgreSQL does not. Keep DDL out of data transactions.
  • Calling setAutoCommit(true) during a transaction commits it, as the JDBC documentation specifies, so the "switch" row was kept.

Frameworks such as Spring's @Transactional implement this same template around your method.

Isolation levels

A transaction's isolation level controls what it can see of other transactions running at the same time. The program uses a reader and a writer connection: the reader reads a price, the writer changes it from 100 to 200, the reader reads again before and after the writer commits. It repeats this for each of the four standard levels.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Isolation {

    static final String URL = "jdbc:h2:mem:iso;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=300";

    static int price(Connection c) throws SQLException {
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT price FROM item WHERE id = 1")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    static void update(Connection c, String sql) throws SQLException {
        try (Statement st = c.createStatement()) {
            st.executeUpdate(sql);
        }
    }

    static String name(int level) {
        return switch (level) {
            case Connection.TRANSACTION_READ_UNCOMMITTED -> "READ_UNCOMMITTED";
            case Connection.TRANSACTION_READ_COMMITTED -> "READ_COMMITTED";
            case Connection.TRANSACTION_REPEATABLE_READ -> "REPEATABLE_READ";
            default -> "SERIALIZABLE";
        };
    }

    public static void main(String[] args) throws Exception {
        try (Connection setup = DriverManager.getConnection(URL, "sa", "")) {
            update(setup, "CREATE TABLE item (id INT PRIMARY KEY, price INT)");
            update(setup, "INSERT INTO item VALUES (1, 100)");
        }

        int[] levels = {Connection.TRANSACTION_READ_UNCOMMITTED,
            Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_REPEATABLE_READ,
            Connection.TRANSACTION_SERIALIZABLE};
        for (int level : levels) {
            try (Connection reader = DriverManager.getConnection(URL, "sa", "");
                 Connection writer = DriverManager.getConnection(URL, "sa", "")) {
                update(writer, "UPDATE item SET price = 100 WHERE id = 1");
                reader.setTransactionIsolation(level);
                reader.setAutoCommit(false);
                writer.setAutoCommit(false);

                int first = price(reader);
                update(writer, "UPDATE item SET price = 200 WHERE id = 1");
                int dirty = price(reader);                       // writer has not committed
                writer.commit();
                int afterCommit = price(reader);                 // same reader transaction
                reader.commit();
                System.out.printf("%-16s first=%d  uncommitted=%d  after commit=%d%n",
                        name(level), first, dirty, afterCommit);
            }
        }

        // Two writers on the same row: the second waits for the first's lock
        try (Connection a = DriverManager.getConnection(URL, "sa", "");
             Connection b = DriverManager.getConnection(URL, "sa", "")) {
            a.setAutoCommit(false);
            b.setAutoCommit(false);
            update(a, "UPDATE item SET price = price + 1 WHERE id = 1");
            long t0 = System.nanoTime();
            try {
                update(b, "UPDATE item SET price = price + 1 WHERE id = 1");
            } catch (SQLException e) {
                System.out.printf("second writer: waited about %d ms, then SQLState %s (%s)%n",
                        Math.round((System.nanoTime() - t0) / 1e8) * 100, e.getSQLState(),
                        e.getClass().getSimpleName());
                b.rollback();
            }
            a.commit();
            System.out.println("after the first writer commits: price=" + price(b));
        }
    }
}

Output:

Output
READ_UNCOMMITTED first=100  uncommitted=200  after commit=200
READ_COMMITTED   first=100  uncommitted=100  after commit=200
REPEATABLE_READ  first=100  uncommitted=100  after commit=100
SERIALIZABLE     first=100  uncommitted=100  after commit=100
second writer: waited about 300 ms, then SQLState HYT00 (JdbcSQLTimeoutException)
after the first writer commits: price=201
  • READ_UNCOMMITTED saw the writer's 200 before it was committed, a dirty read. Had the writer rolled back, the reader would have acted on a price that never existed.
  • READ_COMMITTED, the default in H2, PostgreSQL, Oracle and SQL Server, hid the uncommitted value but saw 200 after the commit, inside the same transaction. Reading the same row twice and getting two values is a non-repeatable read.
  • REPEATABLE_READ and SERIALIZABLE kept showing 100 for the rest of the transaction: the reader works on a consistent snapshot. MySQL's InnoDB uses REPEATABLE_READ as its default.
  • Isolation does not stop two writers from colliding. The second writer tried to update the row the first had locked, waited about 300 ms (the LOCK_TIMEOUT set in the URL), and failed with SQLState HYT00, a timeout. Once the first writer committed, the price was 201: only one increment happened.
Standard isolation levels
LevelPreventsStill allows
READ_UNCOMMITTEDNothingDirty reads of uncommitted data
READ_COMMITTEDDirty readsNon-repeatable reads, phantoms
REPEATABLE_READDirty and non-repeatable readsPhantoms in the standard; many databases prevent them too
SERIALIZABLEAll threeTransactions may fail and need a retry

Lost updates and optimistic locking

The most common concurrency bug in database code is not an isolation problem at all. Two users, Alice and Bob, each sell one unit of a product with stock 10. When each reads the stock, subtracts one in Java and writes the result back, one sale disappears.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LostUpdate {

    static final String URL = "jdbc:h2:mem:lost;DB_CLOSE_DELAY=-1";

    static int[] read(Connection c) throws SQLException {
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT stock, version FROM product WHERE id = 1")) {
            rs.next();
            return new int[] {rs.getInt(1), rs.getInt(2)};
        }
    }

    static void reset(Connection c) throws SQLException {
        try (Statement st = c.createStatement()) {
            st.executeUpdate("UPDATE product SET stock = 10, version = 0");
        }
    }

    // Optimistic locking: the update only succeeds if nobody changed the row since we read it
    static int sell(Connection c, int stockSeen, int versionSeen) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement("UPDATE product SET stock = ?, "
                + "version = version + 1 WHERE id = 1 AND version = ?")) {
            ps.setInt(1, stockSeen - 1);
            ps.setInt(2, versionSeen);
            return ps.executeUpdate();
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection alice = DriverManager.getConnection(URL, "sa", "");
             Connection bob = DriverManager.getConnection(URL, "sa", "");
             Statement st = alice.createStatement()) {
            st.execute("CREATE TABLE product (id INT PRIMARY KEY, stock INT, version INT)");
            st.execute("INSERT INTO product VALUES (1, 10, 0)");

            // 1. Read, compute in Java, write back: the classic lost update
            int a = read(alice)[0];
            int b = read(bob)[0];
            try (Statement s1 = alice.createStatement(); Statement s2 = bob.createStatement()) {
                s1.executeUpdate("UPDATE product SET stock = " + (a - 1) + " WHERE id = 1");
                s2.executeUpdate("UPDATE product SET stock = " + (b - 1) + " WHERE id = 1");
            }
            System.out.println("read-modify-write: two sales, stock now " + read(alice)[0]);

            // 2. Let the database do the arithmetic in one statement
            reset(alice);
            try (Statement s1 = alice.createStatement(); Statement s2 = bob.createStatement()) {
                s1.executeUpdate("UPDATE product SET stock = stock - 1 WHERE id = 1");
                s2.executeUpdate("UPDATE product SET stock = stock - 1 WHERE id = 1");
            }
            System.out.println("atomic UPDATE:     two sales, stock now " + read(alice)[0]);

            // 3. Optimistic locking with a version column
            reset(alice);
            int[] seenA = read(alice);
            int[] seenB = read(bob);
            System.out.println("optimistic: alice updated " + sell(alice, seenA[0], seenA[1])
                    + " row, bob updated " + sell(bob, seenB[0], seenB[1]) + " rows");
            int[] again = read(bob);                              // bob re-reads and retries
            System.out.println("bob retries with version " + again[1] + ": updated "
                    + sell(bob, again[0], again[1]) + " row, stock now " + read(alice)[0]);
        }
    }
}

Output:

Output
read-modify-write: two sales, stock now 9
atomic UPDATE:     two sales, stock now 8
optimistic: alice updated 1 row, bob updated 0 rows
bob retries with version 1: updated 1 row, stock now 8
  • Both read 10 and both wrote 9, so after two sales the stock was 9 instead of 8: a lost update. Every isolation level allows this pattern in auto-commit mode, because each statement is correct on its own.
  • The atomic UPDATE product SET stock = stock - 1 lets the database read and write the row in one locked step, and the stock correctly reached 8. When the change can be written as one statement, this is the simplest fix.
  • With optimistic locking, every row has a version number, and the update includes WHERE version = ?. Alice's update matched and raised the version to 1; Bob's matched 0 rows, which told him the row had changed since he read it. He re-read, retried with version 1, and the stock reached 8. JPA's @Version works exactly like this.
  • The pessimistic alternative is SELECT ... FOR UPDATE inside a transaction, which locks the row until commit, so the second user waits, as the lock timeout in the previous section showed.

Batch inserts and what they save

addBatch() queues a set of parameters, and executeBatch() sends the queued rows together. The program inserts 20,000 rows into a file-based H2 database three ways, to separate two different costs: one commit per row, and one call per row. Each way runs 4 times; the first is a warm-up and the best of the other 3 is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 21.

Java
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class BatchSpeed {

    static final int ROWS = 20000;
    static final String SQL = "INSERT INTO event VALUES (?, ?)";

    interface Load {
        void run(Connection c) throws SQLException;
    }

    static long bestOf3(Connection c, boolean autoCommit, Load load) throws SQLException {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 4; run++) {                       // run 0 is a warm-up
            c.setAutoCommit(true);
            try (Statement st = c.createStatement()) {
                st.execute("TRUNCATE TABLE event");
            }
            c.setAutoCommit(autoCommit);
            long t0 = System.nanoTime();
            load.run(c);
            if (!autoCommit) {
                c.commit();
            }
            if (run > 0) {
                best = Math.min(best, System.nanoTime() - t0);
            }
        }
        return best / 1000000;
    }

    static void rowByRow(Connection c) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement(SQL)) {
            for (int i = 0; i < ROWS; i++) {
                ps.setInt(1, i);
                ps.setString(2, "click");
                ps.executeUpdate();
            }
        }
    }

    static void batched(Connection c) throws SQLException {
        try (PreparedStatement ps = c.prepareStatement(SQL)) {
            for (int i = 0; i < ROWS; i++) {
                ps.setInt(1, i);
                ps.setString(2, "click");
                ps.addBatch();
                if ((i + 1) % 1000 == 0) {
                    ps.executeBatch();                           // send 1,000 rows at once
                }
            }
            ps.executeBatch();                                   // the remainder, if any
        }
    }

    public static void main(String[] args) throws Exception {
        // A file-based database rather than an in-memory one
        String url = "jdbc:h2:" + Files.createTempDirectory("h2") + "/db";
        try (Connection c = DriverManager.getConnection(url, "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE event (id INT PRIMARY KEY, kind VARCHAR(10))");
            long a = bestOf3(c, true, BatchSpeed::rowByRow);
            long b = bestOf3(c, false, BatchSpeed::rowByRow);
            long d = bestOf3(c, false, BatchSpeed::batched);
            System.out.printf("%,d rows into a file-based H2 database, best of 3 runs%n", ROWS);
            System.out.printf("row by row, auto-commit (one commit per row): %5d ms%n", a);
            System.out.printf("row by row, one transaction:                  %5d ms%n", b);
            System.out.printf("batches of 1,000, one transaction:            %5d ms%n", d);
        }
    }
}

Output of the batch timing run:

Output
20,000 rows into a file-based H2 database, best of 3 runs
row by row, auto-commit (one commit per row):    92 ms
row by row, one transaction:                     64 ms
batches of 1,000, one transaction:               31 ms
  • Committing once instead of 20,000 times was faster in every run, by roughly a third to a half. Each commit has fixed work to do: ending the transaction and recording it in the store.
  • The gain from batching on top of the single transaction varied a lot between runs, from almost nothing to about twice as fast. H2 here runs inside the same JVM, so there is no network round trip for a batch to save, only some per-call work.
  • With a database server over a network, each unbatched row costs a round trip of typically a fraction of a millisecond or more, and 20,000 round trips add up to seconds; there batching is usually the larger win. For MySQL, add rewriteBatchedStatements=true to the URL so the driver combines the rows into multi-row inserts.
  • Batches of a few hundred to a few thousand rows are a good default; one huge batch uses a lot of memory on both sides.

When a row in a batch fails

A batch is a list of statements, so one of them can fail while others succeed. The program inserts ids 101, 102, 5 and 103 into a table that already contains id 5, once in auto-commit mode and once inside a transaction.

Java
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

public class BatchFailure {

    static int count(Connection c) throws SQLException {
        try (Statement st = c.createStatement();
             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM event")) {
            rs.next();
            return rs.getInt(1);
        }
    }

    static void tryBatch(Connection c, boolean inTransaction) throws SQLException {
        c.setAutoCommit(!inTransaction);
        try (PreparedStatement ps = c.prepareStatement("INSERT INTO event VALUES (?, ?)")) {
            for (int id : new int[] {101, 102, 5, 103}) {        // id 5 already exists
                ps.setInt(1, id);
                ps.setString(2, "view");
                ps.addBatch();
            }
            ps.executeBatch();
        } catch (BatchUpdateException e) {
            System.out.println((inTransaction ? "in a transaction" : "auto-commit     ")
                    + ": update counts " + Arrays.toString(e.getUpdateCounts())
                    + ", SQLState " + e.getSQLState());
            if (inTransaction) {
                c.rollback();
            }
        }
        System.out.println("  rows afterwards: " + count(c));
        c.setAutoCommit(true);
        try (Statement st = c.createStatement()) {
            st.execute("DELETE FROM event WHERE id > 100");
        }
    }

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection("jdbc:h2:mem:fail", "sa", "");
             Statement st = c.createStatement()) {
            st.execute("CREATE TABLE event (id INT PRIMARY KEY, kind VARCHAR(10))");
            st.execute("INSERT INTO event SELECT X, 'click' FROM SYSTEM_RANGE(1, 10)");
            System.out.println("rows before: " + count(c) + "; batch inserts ids 101, 102, 5, 103");
            System.out.println("EXECUTE_FAILED = " + Statement.EXECUTE_FAILED
                    + ", SUCCESS_NO_INFO = " + Statement.SUCCESS_NO_INFO);
            tryBatch(c, false);
            tryBatch(c, true);

            // A successful batch returns one update count per queued statement
            try (PreparedStatement ps = c.prepareStatement(
                    "UPDATE event SET kind = ? WHERE id <= ?")) {
                ps.setString(1, "a");
                ps.setInt(2, 3);
                ps.addBatch();
                ps.setString(1, "b");
                ps.setInt(2, 0);
                ps.addBatch();
                System.out.println("update batch counts: " + Arrays.toString(ps.executeBatch()));
            }
        }
    }
}

Output:

Output
rows before: 10; batch inserts ids 101, 102, 5, 103
EXECUTE_FAILED = -3, SUCCESS_NO_INFO = -2
auto-commit     : update counts [1, 1, -3, 1], SQLState 23505
  rows afterwards: 13
in a transaction: update counts [1, 1, -3, 1], SQLState 23505
  rows afterwards: 10
update batch counts: [3, 0]
  • executeBatch threw BatchUpdateException with SQLState 23505, a unique constraint violation. Its getUpdateCounts() was [1, 1, -3, 1]: H2 continued after the failure and marked the third statement with Statement.EXECUTE_FAILED (-3). Drivers differ here: others stop at the first failure and return only the counts before it, so code must handle both shapes.
  • In auto-commit mode, the three good rows stayed, 13 rows in total, and the batch was half applied. Inside a transaction, rollback() removed them, and the table still held its original 10 rows. Run batches inside a transaction unless partial results are acceptable.
  • A successful batch returns one count per statement: [3, 0] for an update that matched 3 rows and one that matched none. A driver may return SUCCESS_NO_INFO (-2) when it does not know the count.

Choosing a transaction strategy

What to use when
SituationUse
Several statements that must succeed togethersetAutoCommit(false), commit, rollback in a helper or @Transactional
Undo part of a long transactionsetSavepoint and rollback(savepoint)
Counter or stock changesOne atomic UPDATE ... SET x = x - 1
Read, edit in the application, write backOptimistic locking with a version column
Short critical section on a few rowsA SELECT with FOR UPDATE in a transaction
Reports that need a consistent viewREPEATABLE_READ or a database snapshot
Thousands of insertsaddBatch in batches of about 1,000, inside one transaction
Schema changesOutside data transactions, because many databases commit on DDL

For the statements used inside transactions, see PreparedStatement; for connections and error codes, see JDBC basics.