1. 程式人生 > >JdbcTemplate 使用了模版模式和回撥函式:

JdbcTemplate 使用了模版模式和回撥函式:

1.T execute(ConnectionCallback<T> action) 主要結構 使用了ConnectionCallback中的方法作為回撥方法
 public <T> T execute(ConnectionCallback<T> action) {
    Connection con = DataSourceUtils.getConnection(getDataSource());
            Connection conToUse = con;
            if (this.nativeJdbcExtractor != null
) { // Extract native JDBC Connection, castable to OracleConnection or the like. conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } else { // Create close-suppressing Connection proxy, also preparing returned Statements.
conToUse = createConnectionProxy(con); } return action.doInConnection(conToUse); } } 2. T execute(StatementCallback<T> action) public <T> T execute(StatementCallback<T> action) throws DataAccessException { Connection con = DataSourceUtils.getConnection(getDataSource()); Statement stmt = null
; 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); } T result = action.doInStatement(stmtToUse); handleWarnings(stmt); return result; } 3. execute(final String sql) :使用內部類的回撥 public void execute(final String sql) throws DataAccessException { if (logger.isDebugEnabled()) { logger.debug("Executing SQL statement [" + sql + "]"); } class ExecuteStatementCallback implements StatementCallback<Object>, SqlProvider { @Override public Object doInStatement(Statement stmt) throws SQLException { stmt.execute(sql); return null; } @Override public String getSql() { return sql; } } execute(new ExecuteStatementCallback()); }