Spring JdbcTemplate RowMapper vs ResultSetExtractor

RowMapper interface allows to map a row of the relations with the instance of user-defined class. It iterates the ResultSet internally and adds it into the collection. So we don't need to write a lot of code to fetch the records as ResultSetExtractor.


Example Comparision

ResultSetExtractor : need to manually create a collection(list) to instore the extract data

public List<Product> getAllProducts(){
		
		String sql = "select * from product";
		
		return jdbcTemplate.query(sql, new ResultSetExtractor<List<Product>>(){

			@Override
			public List<Product> extractData(ResultSet rs)
					throws SQLException, DataAccessException {
				
				List<Product> list = new ArrayList<Product>();
				
				while (rs.next()) {
					
					Product product = new Product();
					
					product.setId(rs.getString(1));
					product.setName(rs.getString(2));
					product.setPrice(rs.getFloat(3));
					
					list.add(product);
					
				}
				
				
				return list;
			}
			
		});

	}

RowMapper : internally adds the data of ResultSet into the collection

public List<Product> getAllProductsRowMapper(){
		
		String sql = "select * from product";
		
		return jdbcTemplate.query(sql, new RowMapper<Product>(){

			@Override
			public Product mapRow(ResultSet rs, int rowNumber) throws SQLException {
				
				Product p = new Product();
				
				p.setId(rs.getString(1));
				p.setName(rs.getString(2));
				p.setPrice(rs.getFloat(3));
				
				return p;
			}
			
		});
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章