新建一个handler包,定义处理器的接口
//结果集处理器,规范处理结果集的方法名称 public interface ResultSetHandler<T>{ T handle(ResultSet rs) throws Exception; }
T作为一种未知类型,表示处理完结果集,最后结果集就是该类型,类型由该方法的调用者决定
在DAOImpl类中,实现上述接口
//把结果集中的每一行数据封装成Product对象 class ProductResultHandler implements ResultSetHandler<List<Product>>{ public List<Product> handle(ResultSet rs) throws Exception { List<Product> list=new ArrayList<Product>(); while(rs.next()) { Product pro=new Product(); pro.setId(rs.getLong("id")); pro.setProductName(rs.getString("productName")); pro.setBrand(rs.getString("brand")); pro.setSupplier(rs.getString("supplier")); pro.setSalePrice(rs.getBigDecimal("salePrice")); pro.setCostPrice(rs.getBigDecimal("costPrice")); pro.setCutoff(rs.getDouble("cutoff")); pro.setDir_id(rs.getLong("dir_id")); list.add(pro); } return list; } }
public List<Product> list() { return JdbcTemplate.query("select * from product",new ProductResultHandler()); }
JdbcTemplate中,
public static <T>T query(String sql,ResultSetHandler<T> rsh,Object...params){ List<Product> list=new ArrayList<>(); Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; try { conn=DruidUtil.getConn(); ps=conn.prepareStatement(sql); //设置占位符 for(int index=0;index<params.length;index++) { ps.setObject(index+1, params[index]); } rs=ps.executeQuery(); return rsh.handle(rs); } catch (Exception e) { e.printStackTrace(); }finally { DruidUtil.close(rs, ps, conn); } throw new RuntimeException("查询出错"); }