Mapping ResultSet to Java Objects in JDBC
Fast recall
Quick revision
Core answer
Whether you can convert rows into domain objects cleanly.
Inlining mapping everywhere, duplicating column reads and bugs.
Extract a RowMapper; mention Spring JdbcTemplate uses exactly this abstraction.
Interview-ready guide
Interview answer
OrderSummary map(ResultSet rs) throws SQLException {
return new OrderSummary(
rs.getLong("order_id"),
rs.getString("customer_name"),
rs.getBigDecimal("total")
);
}The SQL should alias id AS order_id when several joined tables expose id. Column labels make the mapping independent of ordinal position, while ordinals can be useful only for tightly controlled performance code.
Mapping ResultSet to Java Objects in JDBC
Direct Answer
ResultSet mapping reads each row's columns, handles SQL nulls and type conversion, and constructs a Java DTO/domain value. Keep the mapping in a focused function or RowMapper so query aliases and object construction stay consistent. Spring JdbcTemplate calls a RowMapper once per row and manages iteration/resource cleanup around it.
Code Example
record User(long id, String name, String email) {}
// RowMapper: maps ONE row to a User
interface RowMapper<T> { T map(ResultSet rs) throws SQLException; }
RowMapper<User> userMapper = rs ->
new User(rs.getLong("id"), rs.getString("name"), rs.getString("email"));
List<User> users = new ArrayList<>();
try (PreparedStatement ps = con.prepareStatement("SELECT id, name, email FROM users");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) users.add(userMapper.map(rs)); // reuse the mapper
}
// Spring: jdbcTemplate.query("SELECT ... ", (rs, rowNum) -> new User(...));
Common Mistakes & Pitfalls
- Inlining mapping everywhere: duplicates column reads; extract a RowMapper.
- Column name typos: a wrong name throws at runtime — keep mapping centralized.
- Ignoring NULLs: use
getObject/wasNullfor nullable columns. - Building objects before
next(): read only after advancing the cursor.
Check your understanding
Answer these without looking back at the article.
- What is a ResultSet in JDBC and how do you iterate it?
- How do you check for NULL values when reading from a ResultSet?
- What happens if you do not close a ResultSet in JDBC?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.