Spring源代码分析-Persist--JdbcTemplate

来源:互联网 发布:吃鸡网络延迟检测 编辑:程序博客网 时间:2024/05/15 13:10
ai 上一节中,我们已经对JdbcDaoSupport和JdbcTemplate有了一定的了解。但是,我们只是初步的了解了JdbcTemplate,至此Spring也只是让我们更方便的获取连接。其实Spring提供了很多强大的功能,使得JdbcTemplate访问数据库,下面,让我们从来看看:

JdbcTemplate:
  1.   public Object execute(String sql, PreparedStatementCallback action) throws DataAccessException {
  2.          return execute(new SimplePreparedStatementCreator(sql), action);
  3.      }
而在JdbcTemplate中有内部类如下:

  1.     private static class SimplePreparedStatementCreator implements PreparedStatementCreator, SqlProvider {

  2.         private final String sql;

  3.         public SimplePreparedStatementCreator(String sql) {
  4.             Assert.notNull(sql, "SQL must not be null");
  5.             this.sql = sql;
  6.         }

  7.         public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
  8.             return con.prepareStatement(this.sql);
  9.         }

  10.         public String getSql() {
  11.             return sql;
  12.         }
  13.     }
SimplePreparedStatementCreator负责从sql String生成查询语句PreparedStatement对象;
  1.     public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action)
  2.             throws DataAccessException {

  3.         Assert.notNull(psc, "PreparedStatementCreator must not be null");
  4.         Assert.notNull(action, "Callback object must not be null");
  5.         //从数据源获取连接
  6.         Connection con = DataSourceUtils.getConnection(getDataSource());
  7.         PreparedStatement ps = null;
  8.         try {
  9.             Connection conToUse = con;
  10.             //利用JdbcTemplate的nativeJdbcExtractor的属性,将这个从数据源得到的数据库连接
  11.             //(有可能是代理类,而不是原生态的数据库连接)中抽取出原生的数据库连接对象
  12.             if (this.nativeJdbcExtractor != null &&
  13.                     this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) {
  14.                 conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
  15.             }
  16.             //从这个数据库连接获取查询语句
  17.             ps = psc.createPreparedStatement(conToUse);
  18.             //将具体的查询语句的属性,比如查询行数等等配置给该查询语句;
  19.             applyStatementSettings(ps);
  20.             PreparedStatement psToUse = ps;
  21.             if (this.nativeJdbcExtractor != null) {
  22.                 //同样,用本地JDBC抽取出原生的查询语句;
  23.                 psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps);
  24.             }
  25.             //执行该查询语句,并且进行处理;
  26.             Object result = action.doInPreparedStatement(psToUse);
  27.             handleWarnings(ps.getWarnings());
  28.             return result;
  29.         }
  30.         catch (SQLException ex) {
  31.             // Release Connection early, to avoid potential connection pool deadlock
  32.             // in the case when the exception translator hasn't been initialized yet.
  33.             if (psc instanceof ParameterDisposer) {
  34.                 ((ParameterDisposer) psc).cleanupParameters();
  35.             }
  36.             String sql = getSql(psc);
  37.             psc = null;
  38.             JdbcUtils.closeStatement(ps);
  39.             ps = null;
  40.             DataSourceUtils.releaseConnection(con, getDataSource());
  41.             con = null;
  42.             throw getExceptionTranslator().translate("PreparedStatementCallback", sql, ex);
  43.         }
  44.         finally {
  45.             if (psc instanceof ParameterDisposer) {
  46.                 ((ParameterDisposer) psc).cleanupParameters();
  47.             }
  48.             //这里将查询语句关闭抽出一个独立的方法;避免异常处理的重复和嵌套;
  49.             JdbcUtils.closeStatement(ps);
  50.             DataSourceUtils.releaseConnection(con, getDataSource());
  51.         }
  52.     }

查询关闭语句:
  1.     public static void closeStatement(Statement stmt) {
  2.         if (stmt != null) {
  3.             try {
  4.                 stmt.close();
  5.             }
  6.             catch (SQLException ex) {
  7.                 logger.debug("Could not close JDBC Statement", ex);
  8.             }
  9.             catch (Throwable ex) {
  10.                 // We don't trust the JDBC driver: It might throw RuntimeException or Error.
  11.                 logger.debug("Unexpected exception on closing JDBC Statement", ex);
  12.             }
  13.         }
  14.     }
执行查询回调方法,给开发者留下了扩展的接口,典型的模板方式的应用:

  1. public interface PreparedStatementCallback {

  2.     //自己实现:
  3.     Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException;

  4. }

接下来,我们可以见到具体的应用;

  1. public Object execute(ConnectionCallback action) throws DataAccessException 

对应于:
  1. public interface ConnectionCallback {

  2.     //用户可以自定义connection操作;
  3.     Object doInConnection(Connection con) throws SQLException, DataAccessException;

  4. }
  1. public Object execute(StatementCallback action) throws DataAccessException {
同理对应于:
  1.  public interface StatementCallback {

  2.      //扩展statement操作;
  3.      Object doInStatement(Statement stmt) throws SQLException, DataAccessException;

  4.  }
以上,我们可以看见Spring位我们准备了三中对象层次的扩展点;

其实,我们利用Spring给我们提供的功能,Jdbc一样也能实现一些程度上的ORM,虽然,有限,但是却能让我们在保证数据库连接效率的同时,也能享受到oo的数据库访问机制;
  1.     public Object query(PreparedStatementCreator psc, ResultSetExtractor rse) throws DataAccessException {
  2.         return query(psc, null, rse);
  3.     }
  1. public Object query(
  2.             PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse)
  3.             throws DataAccessException {

  4.         Assert.notNull(rse, "ResultSetExtractor must not be null");
  5.         if (logger.isDebugEnabled()) {
  6.             String sql = getSql(psc);
  7.             logger.debug("Executing SQL query" + (sql != null ? " [" + sql  + "]" : ""));
  8.         }
  9.         //利用了上面介绍的扩展点之一,查询到了结果集合,并且用ResultSetExtractor对结果的集合进行了处理;
  10.         return execute(psc, new PreparedStatementCallback() {
  11.             public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
  12.                 ResultSet rs = null;
  13.                 try {
  14.                     if (pss != null) {
  15.                         pss.setValues(ps);
  16.                     }
  17.                     rs = ps.executeQuery();
  18.                     ResultSet rsToUse = rs;
  19.                     if (nativeJdbcExtractor != null) {
  20.                         rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
  21.                     }
  22.                     return rse.extractData(rsToUse);
  23.                 }
  24.                 finally {
  25.                     JdbcUtils.closeResultSet(rs);
  26.                     if (pss instanceof ParameterDisposer) {
  27.                         ((ParameterDisposer) pss).cleanupParameters();
  28.                     }
  29.                 }
  30.             }
  31.         });
  32.     }

结果集的解压器接口如下:
  1. public interface ResultSetExtractor {

  2.     //可以在这里对结果集进行处理,转化成为对象;
  3.     Object extractData(ResultSet rs) throws SQLException, DataAccessException;

  4. }


如下:
  1. public class CoreyExtractor implements ResultSetExtractor {

  2.     public Object extractData(ResultSet rs) throws SQLException,
  3.             DataAccessException {
  4.         List<Person> customers=new ArrayList()<Person>;
  5.          while(rs.next()){
  6.              Person customer=new Person();
  7.              customer.setName(rs.getString(1));
  8.              customer.setAge(rs.getInt(2));
  9.              customers.add(customer);
  10.          }
  11.          return customers;
  12.     }

  13. }


这样,就能返回对象了;

同样,存在一下方法:
  1.     public List query(String sql, Object[] args, RowMapper rowMapper)
  2.             throws DataAccessException {
  3.         return query(sql, args, new RowMapperResultReader(rowMapper));
  4.     }
  1. public interface RowCallbackHandler {

  2.       
  3.         /*
  4.         处理单行。
  5.         person.setName(rs.getString(1));
  6.         person.setAge(rs.getInt(2));
  7.         return person;
  8.         */   
  9.     void processRow(ResultSet rs) throws SQLException;

  10. }

  1. public interface ResultReader extends RowCallbackHandler {
  2.      
  3.     //再此基础上可以实现处理多行;
  4.     List getResults();

  5. }


  1. public interface RowMapper {
  2.         
  3.         //实现行对应;并且行与行之间可以进行判断;
  4.         //这也是他比单纯的RowCallBackHandler好的地方;
  5.     Object mapRow(ResultSet rs, int rowNum) throws SQLException; 

  6. }


  1. public List query(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)
  2.             throws DataAccessException {
  3.         return query(sql, args, argTypes, new RowMapperResultReader(rowMapper));
  4.     }
  1.     public List query(String sql, Object[] args, RowCallbackHandler rch)
  2.             throws DataAccessException {
  3.         return query(sql, new ArgPreparedStatementSetter(args), rch);
  4.     }

  1.     public List query(String sql, PreparedStatementSetter pss, final RowCallbackHandler rch)
  2.             throws DataAccessException {
  3.         return (List) query(sql, pss, new RowCallbackHandlerResultSetExtractor(rch));
  4.     }
从对单行的处理,一直委托到给结果集解压器处理;而这个具体的解压器如下:
  1.     private static class RowCallbackHandlerResultSetExtractor implements ResultSetExtractor {

  2.         private final RowCallbackHandler rch;

  3.         public RowCallbackHandlerResultSetExtractor(RowCallbackHandler rch) {
  4.             this.rch = rch;
  5.         }

  6.         public Object extractData(ResultSet rs) throws SQLException {
  7.             //一行行的处理;实现了RowCallBackHandler
  8.            while (rs.next()) {
  9.                 this.rch.processRow(rs);
  10.             }
  11.             //实现整个结果集的处理,实现了RowCallBackHandler的子接口ResultReader;
  12.             if (this.rch instanceof ResultReader) {
  13.                 return ((ResultReader) this.rch).getResults();
  14.             }
  15.             else {
  16.                 return null;
  17.             }
  18.         }
  19.     }
通过这样的一种机制,我们可以直接把结果集合转化成为对象数组;让我们可以像Hibernate一样,直接从数据库里面拿到对象;
从下面的类图结构,可以清晰的看见适配器模式的影子;



我们能够用jdbc从数据库里面直接查询对象,那么有人不禁想问,我们能不能想Hibernate一样,把对象直接更新到数据库里面去呢,答案是肯定的,下面,就像我们来看一下:
我们就要用到SqlUpdate:






经典的运用了模板模式;如下实现;


  1. public class CoreySqlUpdate extends SqlUpdate {
  2.   
  3.     public CoreySqlUpdate(DataSource ds){
  4.         super(ds,"insert into Persons(id,name,age) values(?,?,?)");
  5.         declareParameter(new SqlParameter(Types.INTEGER));
  6.         declareParameter(new SqlParameter(Types.VARCHAR));
  7.         declareParameter(new SqlParameter(Types.INTEGER));
  8.         compile();
  9.     }
  10.     
  11.     public int insertPerson(Person person){
  12.         super.update(person.getId(),person.getName(),person.getAge());
  13.     }
  14. }



我们再来看一下实现代码:

  1.     public SqlUpdate(DataSource ds, String sql) {
  2.         setDataSource(ds);
  3.         setSql(sql);
  4.     }
设置了数据源和执行sql代码;

  1.     public void declareParameter(SqlParameter param) throws InvalidDataAccessApiUsageException {
  2.         if (isCompiled()) {
  3.             throw new InvalidDataAccessApiUsageException("Cannot add parameters once the query is compiled");
  4.         }
  5.         this.declaredParameters.add(param);
  6.     }
将参数类型注册到declaredParameters
  1. public final void compile() throws InvalidDataAccessApiUsageException {
  2.         if (!isCompiled()) {
  3.             if (getSql() == null) {
  4.                 throw new InvalidDataAccessApiUsageException("Property 'sql' is required");
  5.             }

  6.             try {
  7.                 this.jdbcTemplate.afterPropertiesSet();
  8.             }
  9.             catch (IllegalArgumentException ex) {
  10.                 throw new InvalidDataAccessApiUsageException(ex.getMessage());
  11.             }   
  12.         
  13.             compileInternal();
  14.             this.compiled = true;

  15.             if (logger.isDebugEnabled()) {
  16.                 logger.debug("RdbmsOperation with SQL [" + getSql() + "] compiled");
  17.             }
  18.         }
  19.     }
编译sql语句;



  1.     protected final void compileInternal() {
  2.   //生成查询语句工厂;
  3.         this.preparedStatementFactory = new PreparedStatementCreatorFactory(getSql(), getDeclaredParameters());
  4.         this.preparedStatementFactory.setResultSetType(getResultSetType());
  5.         this.preparedStatementFactory.setUpdatableResults(isUpdatableResults());
  6.         this.preparedStatementFactory.setReturnGeneratedKeys(isReturnGeneratedKeys());
  7.         if (getGeneratedKeysColumnNames() != null) {
  8.             this.preparedStatementFactory.setGeneratedKeysColumnNames(getGeneratedKeysColumnNames());
  9.         }
  10.         this.preparedStatementFactory.setNativeJdbcExtractor(getJdbcTemplate().getNativeJdbcExtractor());
  11.                //钩子方法,可以进行扩展;
  12.         onCompileInternal();
  13.     }

  14.     /**
  15.      * Hook method that subclasses may override to post-process compilation.
  16.      * This implementation does nothing.
  17.      * @see #compileInternal
  18.      */
  19.     protected void onCompileInternal() {
  20.     }
在执行更新的时候,首先进行数据验证:

  1. protected void validateParameters(Object[] parameters) throws InvalidDataAccessApiUsageException {
  2.         checkCompiled();

  3.         int declaredInParameters = 0;
  4.         Iterator it = this.declaredParameters.iterator();
  5.         while (it.hasNext()) {
  6.             SqlParameter param = (SqlParameter) it.next();
  7.             if (param.isInputValueProvided()) {
  8.                 if (!supportsLobParameters() &&
  9.                         (param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
  10.                     throw new InvalidDataAccessApiUsageException(
  11.                             "BLOB or CLOB parameters are not allowed for this kind of operation");
  12.                 }
  13.                 declaredInParameters++;
  14.             }
  15.         }

  16.         validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters);
  17.     }
在执行查询语句:
  1. int rowsAffected = getJdbcTemplate().update(newPreparedStatementCreator(params));
  1. protected final PreparedStatementCreator newPreparedStatementCreator(Object[] params) {
  2.         return this.preparedStatementFactory.newPreparedStatementCreator(params);
  3.     }
执行的查询语句是工厂生成的;
如此一来,我们就能够往数据库中直接插入对象,不过再次之前的对象与数据库之间的映射规则我们必须制定,就好比Hibernate的hbm.xml文件一样;

在这一小节中,体现了回调的实现是采用外部类的模板模式,面向接口编程,而我们可以提供具体的回调接口,比如缺省适配器等等,将扩展的点进一步专业细化,比如由PreparedStatementCallBack回调接口的接口方法中实现中,再次采用模板模式模式,我们可以实现ResultSet与对象的映射;

public Object query(final String sql, final ResultSetExtractor rse) throws DataAccessException {
        Assert.notNull(sql, "SQL must not be null");
        Assert.notNull(rse, "ResultSetExtractor must not be null");
        if (logger.isDebugEnabled()) {
            logger.debug("Executing SQL query [" + sql + "]");
        }

        class QueryStatementCallback implements StatementCallback, SqlProvider {
            public Object doInStatement(Statement stmt) throws SQLException {
                ResultSet rs = null;
                try {
                    rs = stmt.executeQuery(sql);
                    ResultSet rsToUse = rs;
                    if (nativeJdbcExtractor != null) {
                        rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
                    }
                    return rse.extractData(rsToUse);
                }
                finally {
                    JdbcUtils.closeResultSet(rs);
                }
            }
            public String getSql() {
                return sql;
            }
        }
        return execute(new QueryStatementCallback());


    }
原创粉丝点击