Spring JDBC - What is ResultSetExtractor?

We will start the post with What ResultSetExtractor is and write an example for it.

1. What is ResultSetExtractor in Spring JDBC?

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.

2. Example usage

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);

You can find the full example code on Github.



Tags: Spring Framework, Spring JDBC, ResultSetExtractor example with JdbcTemplate

← Back home