JDBC Transactions: Commit, Rollback, Isolation, Save Points and Batch Updates
Group statements into transactions with setAutoCommit, commit and rollback, choose isolation levels and understand dirty, non-repeatable and phantom reads, retry deadlocks, use save points, speed up bulk changes with batch updates, and map advanced SQL types like ARRAY, UUID, JSON and SQLXML.
kvi5hnuCode Sprout team member12 min readOn this page
Transferring money means two updates: one account is debited and another credited. If the program crashes or a constraint fails between the two, the money must not simply vanish. A transaction groups statements so that either all of them take effect or none does. This article shows how to control transactions from JDBC, how concurrent transactions affect each other, and how save points and batch updates fit in. It ends with the less common SQL types.
ACID in one paragraph
Databases promise four properties for transactions. Atomicity: all changes or none. Consistency: constraints hold at the end of every transaction. Isolation: concurrent transactions don't see each other's half-finished work, to a configurable degree. Durability: once committed, changes survive crashes. JDBC gives you the controls for the first and third. The database implements them.
Auto-commit, commit and rollback
A new connection is in auto-commit mode: every statement is its own transaction and is committed as soon as it completes. To group statements, turn auto-commit off. Then a transaction starts with the first statement and lasts until you call commit() or rollback():
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
debit.executeUpdate();
credit.executeUpdate();
conn.commit();
} catch (SQLException e) {
conn.rollback(); // undo everything since the last commit
throw e;
} finally {
conn.setAutoCommit(autoCommit);
}
Some rules to keep in mind:
- Roll back on any failure, including runtime exceptions in your own code, before the connection goes back to a pool. Otherwise the next user of the connection inherits an open transaction with half-done changes. Pools usually roll back on return, but don't rely on it.
- Calling
setAutoCommit(true)during a transaction commits it. - What happens to an open transaction when you close a connection without committing depends on the driver. Many roll back, Oracle commits. Always end transactions explicitly.
- DDL statements like
CREATE TABLEcommit implicitly in Oracle, MySQL and H2, so they can't be rolled back there (and they also commit the work done before them in the same transaction). PostgreSQL and SQL Server handle them transactionally. - Keep transactions short. They hold locks (or old row versions) until they end, so a transaction left open while waiting for a user blocks other work.
In frameworks, transactions are usually declarative. A method annotated with Spring's or Jakarta's @Transactional gets exactly this begin, commit or rollback logic wrapped around it.
Isolation levels
When transactions run concurrently, three classic anomalies can occur:
- Dirty read: a transaction sees another transaction's changes before they are committed. If those are rolled back, it has seen data that never existed.
- Non-repeatable read: a transaction reads the same row twice and gets different values, because another transaction committed a change in between.
- Phantom read: a transaction runs the same query twice and gets different rows, because another transaction inserted or deleted matching rows.
The SQL standard defines four isolation levels that rule out more and more of these, and JDBC has a constant for each:

Set the level with conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ) before a transaction starts. DatabaseMetaData.supportsTransactionIsolationLevel tells you what's available. Databases implement the levels differently. Most use multiversion concurrency control, where readers see a snapshot and don't block writers. PostgreSQL's REPEATABLE READ also prevents phantoms, and its SERIALIZABLE detects conflicts and aborts one of the transactions. Oracle offers only READ COMMITTED and SERIALIZABLE. Higher levels cost either waiting (with locking) or aborted transactions (with snapshots).
READ COMMITTED is the most common default. It still allows lost updates: two transactions read a balance, both add to it, and one write overwrites the other. Prevent that with an atomic statement (SET balance = balance + ?), with SELECT ... FOR UPDATE to lock the rows you're about to change, with optimistic locking (a version column checked in the WHERE clause), or with a higher isolation level.
Deadlocks and retries
Two transactions that lock rows in opposite order can wait for each other forever. Databases detect such deadlocks and abort one of the transactions with an SQLState of class 40 (40001 serialization failure, 40P01 deadlock in PostgreSQL), reported as SQLTransactionRollbackException. Serializable snapshot isolation produces the same errors on conflicts. The right response is to roll back and run the whole transaction again, a limited number of times. Lock rows in a consistent order (for example, by ID) to make deadlocks rarer.
Save points
A save point marks a position inside a transaction. rollback(savepoint) undoes only the work done after it, and the transaction continues:
conn.setAutoCommit(false);
insertOrder.executeUpdate();
Savepoint beforeCoupon = conn.setSavepoint("coupon");
try {
applyCoupon.executeUpdate();
} catch (SQLException e) {
conn.rollback(beforeCoupon); // the order stays, the coupon doesn't
}
conn.commit();
setSavepoint() creates an unnamed save point (getSavepointId), and setSavepoint(name) a named one (getSavepointName). releaseSavepoint frees one you no longer need, and all of them go away when the transaction ends. In PostgreSQL, an error inside a transaction makes every later statement fail until you roll back, either completely or to a save point. That makes save points the standard way to continue after an expected error there.
Batch updates
Sending thousands of INSERTs one at a time costs a network round trip each. A batch collects statements and sends them together:
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO accounts VALUES (?, ?, ?)")) {
for (Account a : accounts) {
ps.setInt(1, a.id());
ps.setString(2, a.owner());
ps.setBigDecimal(3, a.balance());
ps.addBatch(); // the current parameters become one batch entry
}
int[] counts = ps.executeBatch(); // one count per entry
}
- With a
PreparedStatement,addBatch()adds the current parameter values. With a plainStatement,addBatch(sql)adds an SQL string. Batches may contain INSERT, UPDATE, DELETE and DDL, but no SELECT.clearBatch()discards the collected entries. executeBatch()returns one update count per entry (executeLargeBatch()returnslongs). A count ofStatement.SUCCESS_NO_INFO(-2) means success with an unknown count.- If an entry fails, the driver throws a
BatchUpdateException. ItsgetUpdateCounts()either has fewer entries than the batch, because the driver stopped at the failure, or marks failed entries withEXECUTE_FAILED(-3) and continued, as H2 does. Run batches with auto-commit off and roll back on failure, so a half-applied batch doesn't remain. - For very large inputs, execute every 500 to 1,000 rows instead of building one huge batch, and commit at sensible intervals.
- Drivers can do much better with special settings. MySQL's
rewriteBatchedStatements=truecombines the batch into multi-row INSERTs, and PostgreSQL'sreWriteBatchedInserts=truedoes likewise. For bulk loading, database-specific tools such as PostgreSQL'sCOPY(available through its driver'sCopyManager) are faster still.
Advanced SQL types
Beyond the common types from article 57, JDBC maps several more:
| SQL type | Java access |
|---|---|
ARRAY | java.sql.Array: rs.getArray, array.getArray(), conn.createArrayOf(typeName, elements), ps.setArray |
TIMESTAMP WITH TIME ZONE | OffsetDateTime through getObject/setObject |
UUID (PostgreSQL, H2) | java.util.UUID through getObject/setObject |
JSON/JSONB | usually as String with vendor-specific casts |
NCHAR, NVARCHAR, NCLOB | national character strings: getNString, setNString, NClob |
ROWID | java.sql.RowId, a database-specific physical row address |
XML | java.sql.SQLXML: getString, getSource/setResult with DOM, SAX or StAX (articles 39 to 47) |
structured and REF types | Struct, Ref, and custom mappings through SQLData and conn.setTypeMap |
Like LOBs, arrays and XML values may be fetched lazily. Call free() when done. Support varies widely between databases, so check the driver's documentation before relying on any of these.
Trying it with H2
This program transfers money between two accounts with a CHECK (balance >= 0) constraint, and a transfer that's too large is rolled back. Two connections then demonstrate isolation, followed by a save point, a successful batch and a batch with two failing entries that gets rolled back. Finally the program stores and reads a UUID, an array, a timestamp with time zone, JSON and an SQLXML value:
import java.math.BigDecimal;
import java.sql.*;
import java.time.OffsetDateTime;
import java.util.*;
public class Transactions {
static final String URL = "jdbc:h2:mem:bank;DB_CLOSE_DELAY=-1";
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection(URL); Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE accounts (id INT PRIMARY KEY, owner VARCHAR(20), balance DECIMAL(10,2) CHECK (balance >= 0))");
stat.executeUpdate("INSERT INTO accounts VALUES (1, 'Ada', 100.00), (2, 'Bob', 50.00)");
}
System.out.println("--- commit and rollback ---");
try (Connection conn = DriverManager.getConnection(URL)) {
System.out.println("auto-commit by default: " + conn.getAutoCommit());
transfer(conn, 1, 2, new BigDecimal("30.00"));
transfer(conn, 1, 2, new BigDecimal("500.00")); // fails: would make Ada's balance negative
printBalances(conn);
}
System.out.println("--- isolation ---");
try (Connection writer = DriverManager.getConnection(URL); Connection reader = DriverManager.getConnection(URL)) {
writer.setAutoCommit(false);
reader.setAutoCommit(false);
writer.createStatement().executeUpdate("UPDATE accounts SET balance = balance + 1000 WHERE id = 2");
System.out.println("reader before the writer commits (no dirty read): " + balance(reader, 2));
writer.commit();
System.out.println("READ_COMMITTED reader after the commit: " + balance(reader, 2));
reader.commit();
reader.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
System.out.println("REPEATABLE_READ reader, first read: " + balance(reader, 2));
writer.createStatement().executeUpdate("UPDATE accounts SET balance = balance - 1000 WHERE id = 2");
writer.commit();
System.out.println("REPEATABLE_READ reader, same transaction: " + balance(reader, 2));
reader.commit();
System.out.println("REPEATABLE_READ reader, new transaction: " + balance(reader, 2));
}
System.out.println("--- save points ---");
try (Connection conn = DriverManager.getConnection(URL); Statement stat = conn.createStatement()) {
conn.setAutoCommit(false);
stat.executeUpdate("INSERT INTO accounts VALUES (3, 'Cleo', 10.00)");
Savepoint beforeBonus = conn.setSavepoint("bonus");
stat.executeUpdate("UPDATE accounts SET balance = balance + 5 WHERE id = 3");
System.out.println("with bonus: " + balance(conn, 3) + " (save point " + beforeBonus.getSavepointName() + ")");
conn.rollback(beforeBonus); // undo only the bonus
conn.commit(); // keep the insert
System.out.println("after rollback to the save point and commit: " + balance(conn, 3));
}
System.out.println("--- batch updates ---");
try (Connection conn = DriverManager.getConnection(URL)) {
System.out.println("supports batch updates: " + conn.getMetaData().supportsBatchUpdates());
conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO accounts VALUES (?, ?, ?)")) {
for (int id = 10; id < 15; id++) {
ps.setInt(1, id);
ps.setString(2, "Customer " + id);
ps.setBigDecimal(3, BigDecimal.valueOf(id));
ps.addBatch();
}
int[] counts = ps.executeBatch();
conn.commit();
System.out.println("counts: " + Arrays.toString(counts));
}
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO accounts VALUES (?, ?, ?)")) {
for (int id : new int[] { 20, 1, 21, -1 }) { // 1 already exists; -1 has a negative balance
ps.setInt(1, id);
ps.setString(2, "Customer " + id);
ps.setBigDecimal(3, BigDecimal.valueOf(id));
ps.addBatch();
}
ps.executeBatch();
conn.commit();
} catch (BatchUpdateException e) {
System.out.println("BatchUpdateException, counts: " + Arrays.toString(e.getUpdateCounts())
+ " (EXECUTE_FAILED = " + Statement.EXECUTE_FAILED + ")");
for (SQLException next = e.getNextException(); next != null; next = next.getNextException())
System.out.println(" " + next.getSQLState());
conn.rollback();
}
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT COUNT(*) FROM accounts")) {
rs.next();
System.out.println("accounts after rollback: " + rs.getInt(1));
}
}
System.out.println("--- advanced types ---");
try (Connection conn = DriverManager.getConnection(URL); Statement stat = conn.createStatement()) {
stat.executeUpdate("CREATE TABLE events (id UUID PRIMARY KEY, scores INTEGER ARRAY, at TIMESTAMP WITH TIME ZONE, details JSON)");
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO events VALUES (?, ?, ?, ? FORMAT JSON)")) {
ps.setObject(1, UUID.fromString("123e4567-e89b-12d3-a456-426614174000"));
ps.setArray(2, conn.createArrayOf("INTEGER", new Integer[] { 7, 9, 4 }));
ps.setObject(3, OffsetDateTime.parse("2026-11-14T09:30:00+01:00"));
ps.setString(4, "{\"source\":\"web\",\"items\":3}");
ps.executeUpdate();
}
try (ResultSet rs = stat.executeQuery("SELECT id, scores, at, details FROM events")) {
rs.next();
UUID id = rs.getObject(1, UUID.class);
Array scores = rs.getArray(2);
Object[] values = (Object[]) scores.getArray(); // element type depends on the driver
OffsetDateTime at = rs.getObject(3, OffsetDateTime.class);
System.out.println(id + " " + Arrays.toString(values) + " base type " + JDBCType.valueOf(scores.getBaseType()) + " " + at + " " + rs.getString(4));
scores.free();
}
try {
SQLXML xml = conn.createSQLXML();
xml.setString("<note>fragile</note>");
System.out.println("SQLXML: " + xml.getString());
xml.free();
} catch (SQLException e) {
System.out.println("SQLXML: " + e.getClass().getSimpleName());
}
}
}
static void transfer(Connection conn, int from, int to, BigDecimal amount) throws SQLException {
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try (PreparedStatement debit = conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?");
PreparedStatement credit = conn.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
credit.setBigDecimal(1, amount); // credit first, so the failure comes second
credit.setInt(2, to);
credit.executeUpdate();
debit.setBigDecimal(1, amount);
debit.setInt(2, from);
debit.executeUpdate();
conn.commit();
System.out.println("transferred " + amount);
} catch (SQLException e) {
conn.rollback();
System.out.println("transfer of " + amount + " rolled back: " + e.getSQLState());
} finally {
conn.setAutoCommit(autoCommit);
}
}
static BigDecimal balance(Connection conn, int id) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement("SELECT balance FROM accounts WHERE id = ?")) {
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getBigDecimal(1); }
}
}
static void printBalances(Connection conn) throws SQLException {
try (Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("SELECT owner, balance FROM accounts ORDER BY id")) {
while (rs.next()) System.out.println(" " + rs.getString(1) + ": " + rs.getBigDecimal(2));
}
}
}
Output with H2 2.3:
--- commit and rollback ---
auto-commit by default: true
transferred 30.00
transfer of 500.00 rolled back: 23513
Ada: 70.00
Bob: 80.00
--- isolation ---
reader before the writer commits (no dirty read): 80.00
READ_COMMITTED reader after the commit: 1080.00
REPEATABLE_READ reader, first read: 1080.00
REPEATABLE_READ reader, same transaction: 1080.00
REPEATABLE_READ reader, new transaction: 80.00
--- save points ---
with bonus: 15.00 (save point bonus)
after rollback to the save point and commit: 10.00
--- batch updates ---
supports batch updates: true
counts: [1, 1, 1, 1, 1]
BatchUpdateException, counts: [1, -3, 1, -3] (EXECUTE_FAILED = -3)
23505
23513
accounts after rollback: 8
--- advanced types ---
123e4567-e89b-12d3-a456-426614174000 [7, 9, 4] base type INTEGER 2026-11-14T09:30+01:00 {"source":"web","items":3}
SQLXML: <note>fragile</note>
The failed transfer had already credited Bob before the debit violated the constraint (23513). The rollback removed that credit too. In the isolation part, the reader at READ COMMITTED saw only committed data, while at REPEATABLE READ it kept seeing its snapshot until its transaction ended. H2 continued the failing batch and marked the duplicate key and the negative balance with -3. The rollback then removed the two successful entries.
The program
The runnable demo builds the reusable piece that every JDBC application needs, a transaction helper. inTransaction turns off auto-commit, runs the work, commits, rolls back on any exception, retries when the failure is transient (SQLState class 40), and restores auto-commit at the end. To watch it without a database, it runs against a dynamic proxy connection that logs the transaction calls and throws failures from a script. (The proxy reuses nativeSQL as its "execute" method.) The scenarios are success, a deadlock followed by success, a constraint violation, which isn't retried, and three deadlocks in a row. The demo then interprets the counts of a BatchUpdateException, splits rows into batches of 1,000, and lists the isolation constants.
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.*;
public class Solution {
@FunctionalInterface
interface Work<T> { T run(Connection conn) throws SQLException; }
// Runs work in a transaction: commit on success, roll back on failure, retry transient failures,
// and always restore the connection's auto-commit mode.
static <T> T inTransaction(Connection conn, int maxAttempts, Work<T> work) throws SQLException {
boolean autoCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
try {
for (int attempt = 1; ; attempt++) {
try {
T result = work.run(conn);
conn.commit();
return result;
} catch (SQLException e) {
conn.rollback();
boolean retry = e instanceof SQLTransientException || e.getSQLState() != null && e.getSQLState().startsWith("40");
if (!retry || attempt == maxAttempts) throw e;
System.out.println(" attempt " + attempt + " failed with " + e.getSQLState() + ", retrying");
} catch (RuntimeException e) {
conn.rollback();
throw e;
}
}
} finally {
conn.setAutoCommit(autoCommit);
}
}
// A fake connection that logs transaction calls; statements fail according to a script
static Connection loggingConnection(List<String> log, Deque<String> failures) {
var autoCommit = new boolean[] { true };
return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class<?>[] { Connection.class },
(proxy, method, args) -> switch (method.getName()) {
case "getAutoCommit" -> autoCommit[0];
case "setAutoCommit" -> { autoCommit[0] = (Boolean) args[0]; log.add("setAutoCommit(" + args[0] + ")"); yield null; }
case "commit", "rollback" -> { log.add(method.getName()); yield null; }
case "nativeSQL" -> { // used here as "execute this statement"
log.add("execute " + args[0]);
String failure = failures.poll();
if (failure == null || failure.equals("ok")) yield args[0];
if (failure.startsWith("40")) throw new SQLTransactionRollbackException("deadlock detected", failure);
throw new SQLIntegrityConstraintViolationException("check constraint violated", failure);
}
default -> throw new SQLFeatureNotSupportedException(method.getName());
});
}
static void scenario(String title, String... failures) {
System.out.println("--- " + title + " ---");
var log = new ArrayList<String>();
Connection conn = loggingConnection(log, new ArrayDeque<>(List.of(failures)));
try {
String result = inTransaction(conn, 3, c -> {
c.nativeSQL("UPDATE accounts SET balance = balance + 30 WHERE id = 2");
c.nativeSQL("UPDATE accounts SET balance = balance - 30 WHERE id = 1");
return "transfer done";
});
System.out.println(" result: " + result);
} catch (SQLException e) {
System.out.println(" gave up: " + e.getClass().getSimpleName() + " " + e.getSQLState());
}
log.forEach(entry -> System.out.println(" " + entry));
}
// Splits many rows into batches of a fixed size; returns the batch sizes it would execute
static <T> List<Integer> chunked(List<T> rows, int batchSize) {
var sizes = new ArrayList<Integer>();
for (int start = 0; start < rows.size(); start += batchSize)
sizes.add(rows.subList(start, Math.min(rows.size(), start + batchSize)).size());
return sizes;
}
public static void main(String[] args) {
scenario("success", "ok", "ok");
scenario("deadlock, then success", "ok", "40P01", "ok", "ok");
scenario("constraint violation: no retry", "ok", "23514");
scenario("three deadlocks", "40001", "40001", "40001");
System.out.println("--- interpreting a BatchUpdateException ---");
int[] counts = { 1, 1, Statement.EXECUTE_FAILED, 1, Statement.SUCCESS_NO_INFO };
var e = new BatchUpdateException("batch failed", "23505", 0, counts, null);
for (int i = 0; i < e.getUpdateCounts().length; i++) {
int c = e.getUpdateCounts()[i];
String meaning = c >= 0 ? c + " row(s)" : c == Statement.SUCCESS_NO_INFO ? "succeeded, count unknown" : "FAILED";
System.out.println(" statement " + i + ": " + meaning);
}
System.out.println("fewer counts than statements would mean the driver stopped at the first failure");
System.out.println("--- splitting 2,350 rows into batches of 1,000 ---");
System.out.println(chunked(Collections.nCopies(2350, "row"), 1000));
System.out.println("--- isolation levels ---");
int[] levels = { Connection.TRANSACTION_NONE, Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED,
Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE };
String[] names = { "NONE", "READ_UNCOMMITTED", "READ_COMMITTED", "REPEATABLE_READ", "SERIALIZABLE" };
for (int i = 0; i < levels.length; i++) System.out.println(" TRANSACTION_" + names[i] + " = " + levels[i]);
}
}
--- success ---
result: transfer done
setAutoCommit(false)
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
execute UPDATE accounts SET balance = balance - 30 WHERE id = 1
commit
setAutoCommit(true)
--- deadlock, then success ---
attempt 1 failed with 40P01, retrying
result: transfer done
setAutoCommit(false)
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
execute UPDATE accounts SET balance = balance - 30 WHERE id = 1
rollback
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
execute UPDATE accounts SET balance = balance - 30 WHERE id = 1
commit
setAutoCommit(true)
--- constraint violation: no retry ---
gave up: SQLIntegrityConstraintViolationException 23514
setAutoCommit(false)
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
execute UPDATE accounts SET balance = balance - 30 WHERE id = 1
rollback
setAutoCommit(true)
--- three deadlocks ---
attempt 1 failed with 40001, retrying
attempt 2 failed with 40001, retrying
gave up: SQLTransactionRollbackException 40001
setAutoCommit(false)
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
rollback
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
rollback
execute UPDATE accounts SET balance = balance + 30 WHERE id = 2
rollback
setAutoCommit(true)
--- interpreting a BatchUpdateException ---
statement 0: 1 row(s)
statement 1: 1 row(s)
statement 2: FAILED
statement 3: 1 row(s)
statement 4: succeeded, count unknown
fewer counts than statements would mean the driver stopped at the first failure
--- splitting 2,350 rows into batches of 1,000 ---
[1000, 1000, 350]
--- isolation levels ---
TRANSACTION_NONE = 0
TRANSACTION_READ_UNCOMMITTED = 1
TRANSACTION_READ_COMMITTED = 2
TRANSACTION_REPEATABLE_READ = 4
TRANSACTION_SERIALIZABLE = 8
Common questions
Do I need a transaction for a single statement? No. In auto-commit mode, each statement is already atomic. Transactions matter when several statements must succeed or fail together, or when you read data and then write based on what you read.
Should a transaction span user interaction, such as a form being edited? Never. A transaction that waits for a user holds locks and a connection for minutes. Read, close, let the user edit, then write in a short transaction, using optimistic locking (a version column) to detect concurrent changes.
What happens if I close a connection without committing? The JDBC specification leaves it to the driver. Most roll back, but some commit (Oracle has historically done so). Always commit or roll back explicitly; pools usually roll back on return as a safety net.
How large should a batch be?
A few hundred to a few thousand statements per executeBatch. Gains flatten beyond that, and very large batches use memory and hold locks longer. Some drivers need a setting to really send batches together, for example rewriteBatchedStatements=true for MySQL or reWriteBatchedInserts=true for PostgreSQL.
How do I retry a transaction safely?
Run the entire transaction again, including the reads, after a rollback, and only for transient failures (SQLState class 40, SQLTransientException). Keep side effects outside the database, such as sending an email, until after the commit, or they repeat with every retry.
Which isolation level should I choose?
Start with the database default, usually READ COMMITTED, and handle the specific anomalies that matter with atomic updates, SELECT ... FOR UPDATE or optimistic locking. Use SERIALIZABLE where correctness is subtle and you're prepared to retry.
API reference
| API | Purpose |
|---|---|
Connection.setAutoCommit, getAutoCommit, commit, rollback | transaction control |
setTransactionIsolation, getTransactionIsolation, TRANSACTION_READ_COMMITTED, ... | isolation levels |
DatabaseMetaData.supportsTransactionIsolationLevel, getDefaultTransactionIsolation | what the database offers |
setSavepoint(), setSavepoint(name), rollback(savepoint), releaseSavepoint | save points |
Savepoint.getSavepointId, getSavepointName | identify a save point |
Statement.addBatch(sql), PreparedStatement.addBatch(), executeBatch, executeLargeBatch, clearBatch | batch updates |
BatchUpdateException.getUpdateCounts, Statement.SUCCESS_NO_INFO, EXECUTE_FAILED | batch results and failures |
SQLTransactionRollbackException | deadlocks and serialization failures (SQLState class 40) |
Array, createArrayOf, SQLXML, createSQLXML, RowId, NClob, Struct, SQLData | advanced types |
Summary
- Connections start in auto-commit mode. Turn it off to group statements, then
commit()on success androllback()on any failure, and restore the mode afterward. - Isolation levels trade consistency for concurrency: READ COMMITTED prevents dirty reads, REPEATABLE READ also non-repeatable reads, and SERIALIZABLE all anomalies. Watch out for lost updates at the lower levels.
- Deadlocks and serialization failures (class 40) call for rolling back and retrying the whole transaction.
- Save points let you undo part of a transaction. Batches send many updates in one round trip. Check
BatchUpdateExceptioncounts and roll back failed batches. - JDBC also maps arrays, UUIDs, time-zone timestamps, XML, national strings and structured types, with varying driver support.
Practice Questions
Your transfer method debits one account, then the credit fails with an exception. Auto-commit is on. What state is the database in?
In auto-commit mode, the debit was committed as soon as it executed, so the money is gone from the first account and never arrived in the second. Turn off auto-commit, execute both statements, and commit only after both succeed, rolling back in the catch block.
Why must code that borrowed a pooled connection roll back on every exception, even a NullPointerException in its own code?
If the transaction stays open, the connection goes back to the pool with uncommitted changes and held locks. The next borrower might commit that half-done work along with its own, or be blocked by the locks. Rolling back in a finally or catch (Exception) path guarantees a clean connection.
Two clerks each read stock = 10, sell 3 and 4 items respectively, and write 7 and 6. The final stock is 6 instead of 3. Which anomaly is this, and how do you prevent it?
A lost update: the second write overwrote the first because both were computed from the same old value. Use an atomic UPDATE products SET stock = stock - ? WHERE id = ?, lock the row with SELECT ... FOR UPDATE before computing, add a version column and include it in the WHERE clause (optimistic locking), or run at an isolation level that detects the conflict.
A batch of 1,000 inserts throws BatchUpdateException and getUpdateCounts() returns an array of length 412. What does that mean?
The driver stopped processing at the first failure. Entries 0 to 411 were executed (their counts are in the array), entry 412 failed, and the rest weren't attempted. With auto-commit off, roll back and fix the data, or retry the remaining entries, depending on your requirements.
When would you use a save point instead of a full rollback?
When part of a transaction may fail in an expected way and the rest should still be committed. For example, an order should be saved even if applying an optional discount fails. Set a save point before the optional step and roll back to it on failure. In PostgreSQL this is also the only way to continue a transaction after a failed statement.
Previous: JDBC Metadata: DatabaseMetaData, ResultSetMetaData and ParameterMetaData
Next: Connection Pools, DataSources and JPA: JDBC in Real Applications
Related reading
- JDBC Metadata: DatabaseMetaData, ResultSetMetaData and ParameterMetaData
- JDBC Row Sets: CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet
- Scrollable and Updatable Result Sets in JDBC
- LOBs, SQL Escapes, Multiple Results and Generated Keys in JDBC
- Prepared Statements in JDBC: Parameters, Reuse and Preventing SQL Injection

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.