在Spring中为了方便用户对数据库的操作,Spring提供了JdbcTemplate以及HibernateTemplate。今天,查看这两个类源码,发现一问题,令我费解,请知道的朋友指点一下。
大致问题就是,在JdbcTemplate的execute(..)方法中,执行SQL抛出异常时,居然没出现回滚代码,具体代码我贴出来,方便大家参考,至于疑问,我也在代码中以注释的形式标出来了,请大家帮忙解释一下,谢谢!
[code="java"]public Object execute(StatementCallback action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(getDataSource());
Statement stmt = null;
try {
Connection conToUse = con;
if (this.nativeJdbcExtractor != null &&
this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
}
stmt = conToUse.createStatement();
applyStatementSettings(stmt);
Statement stmtToUse = stmt;
if (this.nativeJdbcExtractor != null) {
stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
}
Object result = action.doInStatement(stmtToUse); //执行SQL语句
SQLWarning warning = stmt.getWarnings();
throwExceptionOnWarningIfNotIgnoringWarnings(warning);
return result;
}
catch (SQLException ex) {
/*
* 加入执行SQL时抛出异常,一般来说应该回滚的,但是现在没有出现con.rollback()
*/
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}[/code]
谢谢大家耐心观看以及分析!