Showing posts with label ResultSetExtractor example in Spring JDBC. Show all posts

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(products);
  }
}

Now, we will use #query method of JdbcTemplate to use this ProductResultSetExtractor to return result.

ProductResponse productResponse = jdbcTemplate.query("select * from product", new ProductResultSetExtractor(new ProductRowMapper()));

log.info(productResponse::toString);

That's it. You can find the full example code on github.