JdbcTemplate类使用DataSource得到一个数据库连接。然后,他调用StatementCreator实例创建要执行的语句。下一步,他调用StatementCallBack完成。
一旦StatementCallBack返回结果,JdbcTemplate类完成所有必要清理工作关闭连接。如果StatementCreator或StatementCallBack抛出异常,JdbcTemplate类会捕获他们,并转换为Spring数据访问异常。
看一个JdbcTemplate里面的比较核心的一个方法:
- //-------------------------------------------------------------------------
-
//
Methods dealing with prepared statements - //-------------------------------------------------------------------------
-
public Object
execute(PreparedStatementCreator psc, PreparedStatementCallback action) -
throws DataAccessException
{ -
Assert.notNull(psc, "PreparedStatementCreator
must not be null"); -
Assert.notNull(action, "Callback
object must not be null"); -
if (logger.isDebugEnabled())
{ -
String
sql = getSql(psc); -
logger.debug("Executing
prepared SQL statement" +
(sql != null ? "
[" +
sql + "]" : "")); - }
-
Connection
con = DataSourceUtils.getConnection(getDataSource()); -
PreparedStatement
ps = null; - try {
-
Connection
conToUse = con; -
if (this.nativeJdbcExtractor
!= null && -
this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements())
{ -
conToUse
= this.nativeJdbcExtractor.getNativeConnection(con); - }
-
ps
= psc.createPreparedStatement(conToUse); - applyStatementSettings(ps);
-
PreparedStatement
psToUse = ps; -
if (this.nativeJdbcExtractor
!= null)
{ -
psToUse
= this.nativeJdbcExtractor.getNativePreparedStatement(ps); - }
-
Object
result = action.doInPreparedStatement(psToUse); - handleWarnings(ps);
- return result;
- }
-
catch (SQLException
ex) { -
//
Release Connection early, to avoid potential connection pool deadlock -
//
in the case when the exception translator hasn't been initialized yet. -
if (psc instanceof ParameterDisposer)
{ -
((ParameterDisposer)
psc).cleanupParameters(); - }
-
String
sql = getSql(psc);