在JdbcTemplate中,RowMapper用于将数据库查询结果集中的每一行映射为一个Java对象。常见的用法有:
- BeanPropertyRowMapper:将列名映射到相同名称的JavaBean属性。
List<User> users = jdbcTemplate.query("SELECT * FROM user",
new BeanPropertyRowMapper<>(User.class));
- RowMapper实现:
public class UserRowMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
}
}
List<User> users = jdbcTemplate.query("SELECT * FROM user", new UserRowMapper());
- Lambda表达式:
List<User> users = jdbcTemplate.query("SELECT * FROM user",
(ResultSet rs, int rowNum) -> {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
return user;
});
- 元组/值对象:
List<User> users = jdbcTemplate.query("SELECT * FROM user",
(rs, rowNum) -> new User(
rs.getInt("id"),
rs.getString("name"),
rs.getInt("age")
));
所以,RowMapper的作用是方便我们将数据库查询结果映射为Java对象,避免手动遍历ResultSet来创建对象,代码简洁易读。