JdbcTemplate查詢數據中兩種處理結果集方法的簡單比較


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM