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中。
