读书人

Spring 学习 JdbcTemplate模板方式

发布时间: 2012-10-25 10:58:57 作者: rapoo

Spring 学习 JdbcTemplate,模板模式,回调

先通过一个小例子,简单使用一下。

?

配置文件 applicationContext.xml

?

?

程序

?

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);handleWarnings(stmt.getWarnings());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.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());}}

这里就用到了 Template 设计模式,估计Spring 的这个模块叫 JdbcTemplate 的原因也在于此。

?

?action.doInStatement(stmtToUse);

?执行主体逻辑,

?

?至于 之后的 catch,finally 等,都是无聊又必须有的 开闭Connection 之类的操作,

?Spring 把他们固定成模板代码,都不用动他们了,

?只需实现Spring 留给我们的一句 :??action.doInStatement(stmtToUse)? 。

?

?Spring 是使用 Java 回调 实现的。

?

update 方法里, 初始化了一个类, UpdateStatementCallback ,

UpdateStatementCallback? 里,doInStatement 方法里,就是要执行的主体代码,

但 update 方法并没有直接调用doInStatement ,

而是把 整个UpdateStatementCallback? 作为参数,传给了 execute 方法,

再由 execute 调用 UpdateStatementCallback?? 的 doInStatement ,

?

很绕,总结一下就是,A 里边有个B,A委托C调用自己的B,

?那为什么A自己不调呢,上边的例子就是一个原因,

A 是我们负责写的类,C 是Spring,

因为 调用B 之前和之后 要做额外操作, 是很烦的工作,所以A就把活推给C了。

?

?

?

?

?

?

?

?

1 楼 yepeiwen520 2009-09-24 看来之后,好像有点明白了。模式在框架中应用好多啊 2 楼 gutou9 2010-07-19 www.uupan.net 网盘资源集散,网盘网赚研究

读书人网 >其他数据库

热点推荐