ResultSet mapping
What you will learn
ResultSet presents rows through a cursor. Convert each row into an ordinary Java value while the result is open, and handle SQL NULL explicitly.
- Iterate a result cursor correctly.
- Distinguish null, zero and absence.
- Map values and generated keys without exposing live resources.
Prerequisite: Java exceptions, interfaces, Optional and testing fundamentals. Database execution is NOT RUN; local JDK-only examples and test doubles are checked separately.
Read a disconnected rowset
import java.sql.Types;import javax.sql.rowset.*;
public class Main { public static void main(String[] args) throws Exception { RowSetMetaDataImpl m = new RowSetMetaDataImpl(); m.setColumnCount(2); m.setColumnName(1, "sku"); m.setColumnType(1, Types.VARCHAR); m.setColumnName(2, "stock"); m.setColumnType(2, Types.INTEGER); try (CachedRowSet r = RowSetProvider.newFactory().createCachedRowSet()) { r.setMetaData(m); r.moveToInsertRow(); r.updateString(1, "PEN"); r.updateNull(2); r.insertRow(); r.moveToCurrentRow(); r.beforeFirst(); while (r.next()) { int stock = r.getInt("stock"); boolean missing = r.wasNull(); System.out.println(r.getString("sku") + ": " + (missing ? "unknown" : stock)); } } }}Locally executed using java.sql.rowset; expected PEN: unknown. A nullable row is synthetic and intentionally differs from the catalog stock constraint.
Cursor positions
A normal forward-only result begins before its first row. next returns true when positioned on a row and false at exhaustion. Read columns by one-based index or unambiguous label; aliases make joins clearer. No result rows is distinct from a row with a NULL column. getInt returns zero for SQL NULL, so call wasNull immediately after that getter or use a supported typed getObject mapping.
Mapping
Construct immutable records or Optional results inside the resource scope. Keep nullable SQL columns distinct from mandatory domain fields; use NOT NULL constraints where appropriate. SQL NUMERIC normally maps to BigDecimal with getBigDecimal, not double when precision matters. For temporal types, check driver support and database semantics; JDBC 4.2 typed getObject can map supported java.time types.
Generated keys
Prepare with RETURN_GENERATED_KEYS, execute the insert, inspect the affected row count, then read getGeneratedKeys while the statement is open. Support and the returned columns are driver-dependent; inspect the driver contract. A generated key is not proof of commit. The repository example assumes one generated numeric identity and fresh auto-commit connections. The disconnected CachedRowSet demonstration exercises cursor and null behavior without a database.
Map a catalog lookup and generated key
import java.sql.*;import java.util.*;import javax.sql.DataSource;
public final class Catalog { private final DataSource source; public Catalog(DataSource source) { this.source = Objects.requireNonNull(source); } public record Item(String sku, int stock) {}
public Optional<Item> find(String sku) throws SQLException { try (Connection c = source.getConnection(); PreparedStatement p = c.prepareStatement( "SELECT sku, stock FROM catalog_item WHERE sku = ?")) { p.setString(1, Objects.requireNonNull(sku)); try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(new Item(r.getString("sku"), r.getInt("stock"))) : Optional.empty(); } } }
public long add(String sku, int stock) throws SQLException { if (stock < 0) throw new IllegalArgumentException("negative stock"); try (Connection c = source.getConnection(); PreparedStatement p = c.prepareStatement( "INSERT INTO catalog_item(sku, stock) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) { p.setString(1, Objects.requireNonNull(sku)); p.setInt(2, stock); if (p.executeUpdate() != 1) throw new SQLException("insert count"); try (ResultSet keys = p.getGeneratedKeys()) { if (!keys.next()) throw new SQLException("missing generated key"); return keys.getLong(1); } } }
public void reserve(String sku, int quantity) throws SQLException { if (quantity <= 0) throw new IllegalArgumentException("positive quantity required"); Objects.requireNonNull(sku); try (Connection c = source.getConnection()) { Tx.run(c, () -> { try (PreparedStatement p = c.prepareStatement( "UPDATE catalog_item SET stock = stock - ? WHERE sku = ? AND stock >= ?")) { p.setInt(1, quantity); p.setString(2, sku); p.setInt(3, quantity); if (p.executeUpdate() != 1) throw new SQLException("missing item or insufficient stock"); } try (PreparedStatement p = c.prepareStatement( "INSERT INTO reservation(sku, quantity) VALUES (?, ?)")) { p.setString(1, sku); p.setInt(2, quantity); if (p.executeUpdate() != 1) throw new SQLException("reservation count"); } }); } }}Compiled with Tx.java; database NOT RUN. Expected successful insert returns a generated numeric key if supported by chosen driver; find maps one record or empty.
Common mistakes
Do not call getters before next, confuse null with zero, call wasNull after reading another column, or return a closed cursor.
Practice
Explain how to map a nullable integer stock field and distinguish a missing row from a row whose stock is unknown. Predict the rowset example.
Use the manual practice hints; explain your reasoning before consulting the private review solution.
Official reading: result · connection · prepared.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
ResultSet mapping — knowledge check
JDBC knowledge check.
Where is a new result cursor normally positioned?
What does getInt return for SQL NULL?
When should wasNull be called?
What does a generated key prove?
What did CachedRowSet demonstrate locally?