Mapping rows to your own classes and records
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Passing a ResultSet around ties every part of a shop app to SQL column names. How can a row become a plain Java object that the rest of the program uses without knowing any SQL?
A Product record that matches the products table
Mapping a row means copying its columns into the fields of a Java object, with a Java name and a Java type for each column.
Load the mobile phones into a list of Product records, then use the list after the connection is closed.
Example 1 · Rows into a List<Product>
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
// One field per column of the products table, with Java names and Java typesrecord Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {}
public class ProductRecordDemo { public static void main(String[] args) throws SQLException { String sql = "SELECT product_id, sku, name, category_id, price, stock, is_active " + "FROM products WHERE category_id = 2 ORDER BY price"; List<Product> mobiles = new ArrayList<>();
try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD")); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { mobiles.add(new Product( rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active"))); } } // the connection is closed here, but the list of records lives on
System.out.println(mobiles.size() + " mobiles loaded"); System.out.println(mobiles.get(0)); for (Product p : mobiles) { System.out.println(" " + p.name() + " - Rs " + p.price() + (p.stock() < 10 ? " (few left)" : "")); } }}3 mobiles loaded Product[id=1, sku=MOB-RN13, name=Redmi Note 13 5G, categoryId=2, price=17999.00, stock=40, active=true] Redmi Note 13 5G - Rs 17999.00 Samsung Galaxy M35 - Rs 19999.00 iPhone 15 128GB - Rs 69900.00 (few left)
What this code does
- Each row becomes one
Product. Column names (product_id,is_active) become Java names (id,active), andpricestays an exactBigDecimal. - The loop over
mobilesruns after thetryblock has closed the connection. The records do not need the database any more. - Printing a record shows every field, which helps when debugging the mapping.
For ShopLite's products table the object is a record: record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active). Column product_id becomes field id, is_active becomes active, and DECIMAL becomes BigDecimal.
Why not pass the ResultSet around? It lives only while its statement and connection are open, and every reader must know the column names and getters. A List<Product> lives on, and the rest of the program works with p.price() instead of rs.getBigDecimal("price"). This is the first step towards clean layers in ShopLite: only the code that talks to the database knows SQL.
One mapRow method used by every query
mapRow is a method that turns the current row of a ResultSet into one object. Every query that returns products calls it inside its while (rs.next()) loop.
Two finder methods share one mapRow; only their SQL differs.
Example 2 · One mapRow, two queries
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {}
public class MapRowDemo { // The only place that knows how a products row becomes a Product static Product mapRow(ResultSet rs) throws SQLException { return new Product( rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active")); }
static List<Product> findByCategory(Connection con, int categoryId) throws SQLException { String sql = "SELECT product_id, sku, name, category_id, price, stock, is_active " + "FROM products WHERE category_id = " + categoryId + " ORDER BY name"; return queryProducts(con, sql); }
static List<Product> findLowStock(Connection con, int below) throws SQLException { String sql = "SELECT product_id, sku, name, category_id, price, stock, is_active " + "FROM products WHERE is_active = TRUE AND stock < " + below + " ORDER BY stock, name"; return queryProducts(con, sql); }
private static List<Product> queryProducts(Connection con, String sql) throws SQLException { List<Product> result = new ArrayList<>(); try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { result.add(mapRow(rs)); } } return result; }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {
System.out.println("Laptops:"); for (Product p : findByCategory(con, 3)) { System.out.println(" " + p.sku() + " " + p.name() + " Rs " + p.price()); }
System.out.println("Low stock (below 10):"); for (Product p : findLowStock(con, 10)) { System.out.println(" " + p.stock() + " left " + p.name()); } } }}Laptops: LAP-HPV15 HP Victus 15 Gaming Rs 64990.00 LAP-IPS3 Lenovo IdeaPad Slim 3 Rs 42990.00 Low stock (below 10): 0 left Logitech M331 Silent Mouse 5 left HP Victus 15 Gaming 8 left iPhone 15 128GB
What this code does
findByCategoryandfindLowStockdiffer only in their SQL. Both hand the SQL toqueryProducts, which loops and callsmapRowfor every row.- If a column is added to
products, only the SELECT lists andmapRowchange; the two finder methods and their callers stay the same.
Without it, each query repeats the seven getters, and when a column is renamed or a field is added you must fix every copy. The copy you miss gives wrong data on one screen of the app.
mapRow reads only the current row and never calls next() itself: moving the cursor stays the job of the loop that calls it. That way mapRow works the same in a while loop for many rows and in an if for one row.
Order of execution
One row, one Product
Tap the steps in the order they happen for each row.
List<Product> for many rows, Optional<Product> for one
Look up a product by id: an Optional<Product> says in its type that the row may not exist.
Example 3 · Optional<Product> for a lookup by id
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Optional;
record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {}
public class FindByIdDemo { static Product mapRow(ResultSet rs) throws SQLException { return new Product(rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active")); }
// Zero or one row: Optional says "maybe" in the return type itself static Optional<Product> findById(Connection con, int productId) throws SQLException { String sql = "SELECT product_id, sku, name, category_id, price, stock, is_active " + "FROM products WHERE product_id = " + productId; try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { if (rs.next()) { return Optional.of(mapRow(rs)); } return Optional.empty(); } }
public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {
Optional<Product> found = findById(con, 5); System.out.println("id 5: " + found.map(Product::name).orElse("not found"));
Optional<Product> missing = findById(con, 42); System.out.println("id 42: " + missing.map(Product::name).orElse("not found"));
// When a missing row is an error for the caller, it says so with orElseThrow try { Product p = findById(con, 42) .orElseThrow(() -> new IllegalArgumentException("No product with id 42")); System.out.println(p); } catch (IllegalArgumentException e) { System.out.println("Cart error: " + e.getMessage()); } } }}id 5: HP Victus 15 Gaming id 42: not found Cart error: No product with id 42
What this code does
findByIdusesif (rs.next()): one row becomesOptional.of(mapRow(rs)), no row becomesOptional.empty().- The caller decides what missing means:
orElse("not found")for a message,orElseThrowfor an error in the cart.
A query that can return any number of rows returns a List<Product>. When nothing matches, the list is empty, never null, so callers can loop over it without a check.
A lookup by primary key returns zero or one row, so it returns an Optional<Product>: Optional.of(mapRow(rs)) inside if (rs.next()), and Optional.empty() otherwise. Returning null for "not found" is the classic mistake: the caller forgets the check, and a NullPointerException appears far away from the query that caused it.
Find the bug
Which line returns null?
Tap the line that can cause a NullPointerException far away.
A lookup by primary key must report "not found" safely.
Round 1 of 2A RowMapper<T> functional interface
RowMapper<T> is a small interface of your own with one method, T mapRow(ResultSet rs) throws SQLException. With one abstract method, a lambda or a method reference can implement it.
One generic query method runs any SELECT; each caller passes only its own mapper.
Example 4 · A generic query method with RowMapper lambdas
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
// Like Function<ResultSet, T>, but its method may throw SQLException@FunctionalInterfaceinterface RowMapper<T> { T mapRow(ResultSet rs) throws SQLException;}
record Category(int id, String name, Integer parentId) {}
record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {
static Product fromRow(ResultSet rs) throws SQLException { return new Product(rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active")); }}
public class RowMapperDemo { // One loop for every query in the program; only the mapper changes static <T> List<T> query(Connection con, String sql, RowMapper<T> mapper) throws SQLException { List<T> result = new ArrayList<>(); try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { result.add(mapper.mapRow(rs)); } } return result; }
public static void main(String[] args) throws SQLException { RowMapper<Category> categoryMapper = rs -> new Category( rs.getInt("category_id"), rs.getString("name"), rs.getObject("parent_id", Integer.class));
try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {
List<Category> categories = query(con, "SELECT category_id, name, parent_id FROM categories ORDER BY category_id LIMIT 3", categoryMapper); categories.forEach(System.out::println);
List<Product> books = query(con, "SELECT product_id, sku, name, category_id, price, stock, is_active " + "FROM products WHERE category_id = 5 ORDER BY name", Product::fromRow); books.forEach(b -> System.out.println(b.name() + " - Rs " + b.price()));
List<String> emails = query(con, "SELECT email FROM customers WHERE phone IS NULL ORDER BY email", rs -> rs.getString("email")); System.out.println("No phone on file: " + emails); } }}Category[id=1, name=Electronics, parentId=null] Category[id=2, name=Mobiles, parentId=1] Category[id=3, name=Laptops, parentId=1] Atomic Habits - Rs 399.00 Clean Code - Rs 499.00 The Pragmatic Programmer - Rs 650.00 No phone on file: [arjun.mehta@example.com, meena.iyer@example.com]
What this code does
queryis written once and returnsList<Category>,List<Product>orList<String>, depending on the mapper passed in.- The mappers are a lambda (
categoryMapper), a method reference (Product::fromRow) and a one-line lambda for a single column. Each may throwSQLExceptionbecause the interface says so. getObject("parent_id", Integer.class)keeps Electronics'NULLparent asnull, as the type-mapping lesson showed.
Why not Function<ResultSet, T>? Every getter can throw the checked SQLException, and Function.apply may not throw checked exceptions, so each lambda would need a try/catch. Declaring throws SQLException on your own interface keeps every mapper a one-line lambda.
The query loop, the resource closing and the list building now live in one place, and each entity only adds its mapper. Spring's JdbcTemplate, used in the Spring Boot section, is built on the same idea and even has an interface called RowMapper.
Fix the error
Fix the mapper type
Read the real compiler error, then pick the line that fixes it.
A mapper is declared with the standard Function type.
Error
Demo.java:6: error: unreported exception SQLException; must be caught or declared to be thrown
Function<ResultSet, String> mapper = rs -> rs.getString("name");
^Records versus classes, and column names in one place
A record is an immutable data class: its fields are final, and equals, hashCode and a readable toString come for free.
A hand-typed column list forgets stock; one shared COLUMNS constant fixes it.
Example 5 · A forgotten column, and the COLUMNS fix
Runs in: a Maven project with the MySQL driver and the ShopLite database
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
record Product(int id, String sku, String name, int categoryId, BigDecimal price, int stock, boolean active) {}
class ProductQueries { // Every products query selects exactly these columns, so mapRow always finds them static final String COLUMNS = "product_id, sku, name, category_id, price, stock, is_active";
static Product mapRow(ResultSet rs) throws SQLException { return new Product(rs.getInt("product_id"), rs.getString("sku"), rs.getString("name"), rs.getInt("category_id"), rs.getBigDecimal("price"), rs.getInt("stock"), rs.getBoolean("is_active")); }
static List<Product> list(Connection con, String sql) throws SQLException { List<Product> result = new ArrayList<>(); try (Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { result.add(mapRow(rs)); } } return result; }}
public class ColumnsInOnePlaceDemo { public static void main(String[] args) throws SQLException { try (Connection con = DriverManager.getConnection( System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {
// Bug: this query was typed by hand and forgot the stock column try { ProductQueries.list(con, "SELECT product_id, sku, name, category_id, price, is_active " + "FROM products WHERE category_id = 6"); } catch (SQLException e) { System.out.println("Hand-typed column list: " + e.getMessage()); }
// Fix: build every query from the one COLUMNS constant List<Product> fashion = ProductQueries.list(con, "SELECT " + ProductQueries.COLUMNS + " FROM products WHERE category_id = 6 ORDER BY name"); System.out.println("With COLUMNS: " + fashion.size() + " products"); fashion.forEach(p -> System.out.println(" " + p.name() + ", stock " + p.stock())); } }}Hand-typed column list: Column 'stock' not found. With COLUMNS: 2 products Cotton Kurta, stock 35 Running Shoes, stock 18
What this code does
- The hand-typed SELECT left out
stock, somapRowfails withColumn 'stock' not found.when it reads the first row. - Building every query from
ProductQueries.COLUMNSguarantees thatmapRowfinds every column it reads.
A record fits rows read from the database well. A normal class is the better choice when the object must change after it is built, or when a framework wants a no-argument constructor and setters, as JPA entities do in the Spring Data JPA section.
Keep the table's column list in one place: a COLUMNS constant next to mapRow, used to build every SELECT. Avoid SELECT * in application code: it fetches columns nobody reads, and it hides which columns the Java code depends on.
COLUMNS, mapRow and the queries move into one ProductDao class, the only class that knows the products table.Next step
Check your understanding
12 quick questions