Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java JDBC batches: inspect update counts and own rollback

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

PreparedStatement batching queues parameter sets for one executeBatch call. The returned counts and a possible BatchUpdateException describe execution, not automatic transaction success.

Operational contract

Some drivers stop after a failed command, while others continue and mark failed positions. SUCCESS_NO_INFO means success without a row count. A caller must decide whether every position met the business invariant, then commit or roll back the owned transaction. The method stages one receipt ID per parameter set and returns raw counts; it requires auto-commit to be disabled. It does not promise that batch execution alone is atomic, and it leaves commit, rollback, and connection lifetime to its caller.

Failure case

A depot sends 47 receipt IDs. If entry 31 violates a uniqueness rule, the caller records the failing batch result, rolls back the transaction, and resolves whether a retry is safe. It does not report 30 or 46 accepted receipts from a count array while leaving the connection open for another request. The IDs need an idempotency rule before a retry after a network failure.

Java code

Java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class ReceiptBatchWriter {
    public static int[] stage(Connection connection, List<String> receiptIds) throws SQLException {
        if (connection.getAutoCommit()) throw new SQLException("Caller must own a transaction");
        try (PreparedStatement statement = connection.prepareStatement(
                "INSERT INTO receipt_intake (receipt_id) VALUES (?)")) {
            for (String receiptId : receiptIds) {
                statement.setString(1, receiptId);
                statement.addBatch();
            }
            return statement.executeBatch();
        }
    }
}

Performance and ownership cost

Binding N rows is O(N) client work and O(N) pending parameter state until execution. Batching can reduce round trips, but the actual transport and server plan depend on the driver. Bound batch size and inspect all returned positions; a database transaction remains the durability boundary.

Common Mistakes

  • Do not interpret SUCCESS_NO_INFO as zero affected rows.
  • Do not assume every driver stops at the first failed command.
  • Do not leave rollback ownership ambiguous after any failure.

Connected lessons

java
jdbc result contracts
jdbc-batch-update-counts
Storage details