现在的位置: 首页 > 综合 > 正文

Spring的JdbcTemplate使用,是否还需要手工或者aop指定关闭conn连接( 使用JdbcTemplate是否需要关闭连接)

2014年01月20日 ⁄ 综合 ⁄ 共 1980字 ⁄ 字号 评论关闭

JdbcTemplate类使用DataSource得到一个数据库连接。然后,他调用StatementCreator实例创建要执行的语句。下一步,他调用StatementCallBack完成。
一旦StatementCallBack返回结果,JdbcTemplate类完成所有必要清理工作关闭连接。如果StatementCreator或StatementCallBack抛出异常,JdbcTemplate类会捕获他们,并转换为Spring数据访问异常。




看一个JdbcTemplate里面的比较核心的一个方法: 

  1. //-------------------------------------------------------------------------  
  2. //
    Methods dealing with prepared statements
      
  3. //-------------------------------------------------------------------------  
  4.   
  5. public Object
    execute(PreparedStatementCreator psc, PreparedStatementCallback action)  
  6.         throws DataAccessException
    {  
  7.   
  8.     Assert.notNull(psc, "PreparedStatementCreator
    must not be null"
    );  
  9.     Assert.notNull(action, "Callback
    object must not be null"
    );  
  10.     if (logger.isDebugEnabled())
    {  
  11.         String
    sql = getSql(psc);  
  12.         logger.debug("Executing
    prepared SQL statement"
     +
    (sql != 
    null ? "
    ["
     +
    sql + 
    "]" : ""));  
  13.     }  
  14.   
  15.     Connection
    con = DataSourceUtils.getConnection(getDataSource());  
  16.     PreparedStatement
    ps = null;  
  17.     try {  
  18.         Connection
    conToUse = con;  
  19.         if (this.nativeJdbcExtractor
    != 
    null &&  
  20.                 this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements())
    {  
  21.             conToUse
    this.nativeJdbcExtractor.getNativeConnection(con);  
  22.         }  
  23.         ps
    = psc.createPreparedStatement(conToUse);  
  24.         applyStatementSettings(ps);  
  25.         PreparedStatement
    psToUse = ps;  
  26.         if (this.nativeJdbcExtractor
    != 
    null)
    {  
  27.             psToUse
    this.nativeJdbcExtractor.getNativePreparedStatement(ps);  
  28.         }  
  29.         Object
    result = action.doInPreparedStatement(psToUse);  
  30.         handleWarnings(ps);  
  31.         return result;  
  32.     }  
  33.     catch (SQLException
    ex) {  
  34.         //
    Release Connection early, to avoid potential connection pool deadlock
      
  35.         //
    in the case when the exception translator hasn't been initialized yet.
      
  36.         if (psc instanceof ParameterDisposer)
    {  
  37.             ((ParameterDisposer)
    psc).cleanupParameters();  
  38.         }  
  39.         String
    sql = getSql(psc);  

抱歉!评论已关闭.