public List<Cat> listCats(){
//多条数据查询
String sql = "select id, name, description, mother_id, createDate from tbl_cat";
/*//方法1、使用RowMapper<Cat>处理结果集
return jdbcTemplate.query(sql, new RowMapper<Cat>(){
@Override
public Cat mapRow(ResultSet rs, int index) throws SQLException {
// TODO Auto-generated method stub
Cat cat = new Cat();
cat.setId(rs.getInt("id"));
cat.setMother_id(rs.getInt("mother_id"));
cat.setDescription(rs.getString("description"));
cat.setCreateDate(rs.getDate("creatDate"));
return cat;
}
});*/
//方法2、使用RowCallbackHandler()
final List<Cat> catList = new ArrayList<Cat>();//在内部匿名类中使用
jdbcTemplate.query(sql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
// TODO Auto-generated method stub
Cat cat = new Cat();
cat.setId(rs.getInt("id"));
cat.setMother_id(rs.getInt("mother_id"));
cat.setDescription(rs.getString("description"));
cat.setCreateDate(rs.getDate("creatDate"));
//####do something
catList.add(cat);
}
});
return catList;
}
两种方法在功能上并没有太大的区别,都是用于定义结果集行的读取逻辑,将ResultSet中的数据映射到对象或者list中。
区别是,使用RowMapper,将直接得到一个List,而RowCallbackHandler并不直接返回数据,而是在processRow()接口方法中自己对得到的数据进行处理。
当处理大结果集时,如果使用RowMapper,结果集中所有数据最终都会映射到List中,占用大量的JVM内存,甚至直接引发OutOfMemroyException异常。这时应该使用RowCallbackHandler接口在processRow()接口方法中处理得到的数据(在//####do something 处),而不是将其添加到List中。