与 ResultsetExtractor 的基本区别在于,您需要自己遍历结果集,比如在 while 循环中。
此接口为您提供一次对整个 ResultSet 的处理。接口方法 extractData(ResultSet rs) 的实现将包含该手动迭代代码。
See one implementation of ResultsetExtractor
虽然像 RowCallbackHandler 这样的回调处理程序,接口方法 processRow(ResultSet rs) 会为您循环。
RowMapper 既可用于映射每一行,也可用于映射整行。
对于整行对象(通过模板方法 jdbcTemplate.query())
public List findAll() {
String sql = "SELECT * FROM EMPLOYEE";
return jdbcTemplate.query(sql, new EmployeeRowMapper());
}
without casting will work
对于单个对象(使用模板方法 jdbcTemplate.queryForObject())
@SuppressWarnings({ "unchecked", "rawtypes" })
public Employee findById(int id) {
String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?";
// jdbcTemplate = new JdbcTemplate(dataSource);
Employee employee = (Employee) jdbcTemplate.queryForObject(sql, new EmployeeRowMapper(), id );
// Method 2 very easy
// Employee employee = (Employee) jdbcTemplate.queryForObject(sql, new Object[] { id }, new BeanPropertyRowMapper(Employee.class));
return employee;
}
@SuppressWarnings("rawtypes")
public class EmployeeRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setId(rs.getInt("ID"));
employee.setName(rs.getString("NAME"));
employee.setAge(rs.getInt("AGE"));
return employee;
}
}
最佳用例:
Row Mapper:当一个ResultSet的每一行都映射到一个域Object时,可以实现为私有内部类。
RowCallbackHandler:当没有从每一行的回调方法返回值时,例如将行写入文件,将行转换为 XML,在添加到集合之前过滤行。非常有效,因为这里没有完成 ResultSet 到 Object 的映射。
ResultSetExtractor: 当多行 ResultSet 映射到单个 Object 时。就像在查询中进行复杂连接时,可能需要访问整个 ResultSet 而不是单行 rs 来构建复杂的 Object,并且您希望完全控制 ResultSet。就像将从 TABLE1 和 TABLE2 的连接返回的行映射到完全重构的 TABLE 聚合。
ParameterizedRowMapper用于创建复杂对象