Spring JDBC - What is RowMapper?

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

1. What is RowMapper in Spring JDBC?

It is an interface of Spring JDBC module which is used by JdbcTemplate to map rows of java.sql.ResultSet. It is typically used when you query data.

2. Example usage of RowMapper

Let's first create a RowMapper which can map products.

class ProductRowMapper implements RowMapper {

@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setDescription(rs.getString("description"));
product.setCategory(rs.getString("category"));
return product;
}
}

Now, we will use this ProductRowMapper in queryForObject method of JdbcTemplate.

Product product = jdbcTemplate.queryForObject("select * from product where id=1", new ProductRowMapper());
log.info(product::toString);

You can see the full example code on Github.



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

← Back home