Skip to main content

Posts

Showing posts with the label ResultSetExtractor example in Spring JDBC

Spring JDBC ResultSetExtractor example

What is ResultSetExtractor? It is an interface used by #query methods of JdbcTemplate . It is better suitable if you want to map one result object per ResultSet otherwise RowMapper is simpler choice to map one row of ResultSet with one object. How to use it? Let's first create a ResultSetExtractor which maps all the rows of ResultSet to single object. For this we will create a ProductResultSetExtractor which returns ProductResponse . public class ProductResultSetExtractor implements ResultSetExtractor { private final RowMapper productRowMapper; public ProductResultSetExtractor(RowMapper productRowMapper) { super(); this.productRowMapper = productRowMapper; } @Override public ProductResponse extractData(ResultSet rs) throws SQLException { final List products = new ArrayList<>(); int rowNum = 0; while(rs.next()) { products.add(productRowMapper.mapRow(rs, rowNum)); rowNum++; } return ProductResponse.of(prod