ResultSet holdability specifies whether a cursor remains open or closes when its transaction commits. Code that reads rows should make its commit boundary explicit.
Java JDBC cursor holdability: choose what commit does to a ResultSet
Operational contract
The sample requests CLOSE_CURSORS_AT_COMMIT, then consumes up to 47 rows before the caller can commit. It does not commit inside the method. Driver support should be checked through DatabaseMetaData and exercised in a database integration test; some drivers may reject the requested combination of type, concurrency, and holdability. A close-at-commit cursor is not a memory limit, so the method also caps returned IDs. The caller owns the Connection and transaction, while this method closes the statement and cursor.
Failure case
An export starts reading receipt IDs and another layer commits the same connection halfway through iteration. With close-at-commit policy, the cursor can close, making the remaining read invalid. This method returns a bounded list before the caller reaches its commit point.
Java code
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ReceiptCursorBeforeCommit {
public static List<Long> ids(Connection connection, long depotId) throws SQLException {
try (PreparedStatement statement = connection.prepareStatement(
"SELECT receipt_id FROM receipts WHERE depot_id = ? ORDER BY receipt_id",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT)) {
statement.setLong(1, depotId);
List<Long> result = new ArrayList<>();
try (ResultSet rows = statement.executeQuery()) {
while (rows.next()) {
if (result.size() == 47) throw new SQLException("Too many receipts");
result.add(rows.getLong(1));
}
}
return List.copyOf(result);
}
}
}Performance and ownership cost
Reading R rows is O(R) application time and O(R) result storage, capped at 47. Query execution, sorting, cursor buffering, and database I/O have additional costs. Holdability controls cursor lifetime at commit, not the number of rows a query can produce.
Common Mistakes
- Do not commit a transaction while still depending on a close-at-commit cursor.
- Do not assume requested holdability is supported on every driver.
- Do not treat cursor holdability as a row or memory cap.
Connected lessons
- Java DatabaseMetaData: check features before depending on them
- Java JDBC fetch size: a hint, not a memory guarantee
- Java JDBC transactions: atomic updates and rollback
- Java SQLWarning: inspect nonfatal database diagnostics before reuse
- Java SQLException chains: preserve SQLState and linked failures
- Java JDBC boundary contracts quiz
- Advanced Java
