Spring JdbcTemplate RowMapper vs ResultSetExtractor

来源:互联网 发布:华为性格测试 知乎 编辑:程序博客网 时间:2024/06/06 20:05

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>>(){@Overridepublic 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>(){@Overridepublic 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;}});}


0 0
原创粉丝点击