持久层封装之JdbcTemplate
Spring对JDBC进行了良好的封装,通过提供相应的模板和辅助类,在相当程度上降低了JDBC操作的复杂性。并且得益于Spring良好的隔离设计,JDBC封装类库可以脱离Spring Context独立使用,也就是说,即使系统并没有采用Spring作为结构性框架,我们也可以单独使用Spring的JDBC部分(spring-dao.jar)来改善我们的代码。
作为对比,首先让我们来看一段传统的JDBC代码:
Connection conn =null; Statement stmt = null; try { conn = dataSource.getConnection(); stmt = con.createStatement(); stmt.executeUpdate("UPDATE user SET age = 18 WHERE id = 'erica'"); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { logger.warn("Exception in closing JDBC Statement", ex); } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { logger.warn("Exception in closing JDBC Connection", ex); } } } JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate .update( "UPDATE user SET age = ? WHERE id = ?", new PreparedStatementSetter() { public void setValues(PreparedStatementSetter ps) throws SQLException { ps.setInt(1, 18); ps.setString(2, "erica"); } } ); final List userList = new ArrayList(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate .query( "SELECT name, sex, address FROM user WHERE age > 18", new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { User user = new User(); user.setId(rs.getString("name")); user.setSex(rs.getString("sex")); user.setAddress(rs.getString("address")); userList.add(product); } });这里传入query方法的有两个参数,第一个是Select查询语句,第二个是一个RowCallbackHandler实例,我们通过RowCallbackHandler对Select语句得到的每行记录进行解析,并为其创建一个User数据对象。实现了手动的OR映射。