在spring里面我们一般是这样来使用模板模式的:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update("UPDATE user SET age = 10 WHERE id = 'erica'");
或者:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate
.update(
"UPDATE user SET age = ? WHERE id = ?",
new PreparedStatementSetter() {
public void setValues(PreparedStatementSetter ps)
throws SQLException {
ps.setInt(1, 18);
ps.setString(2, "erica");
}
}
);
那么具体在spring里面他是怎么运作的呢?
下面以query查询为例:
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations, InitializingBean {
。。。。。。。。。。。。。。。。。。。。。。。。。
protected Object query(
PreparedStatementCreator psc, final PreparedStatementSetter pss, final ResultSetExtractor rse)
throws DataAccessException {
if (logger.isDebugEnabled()) {
String sql = getSql(psc);
logger.debug("Executing SQL query" + (sql != null ? " [" + sql + "]" : ""));
}
return execute(psc, new PreparedStatementCallback() {
//此处以 PreparedStatementCallback 为参数调用 execute()方法,在execute()方法里面回调传入的方法。在回调方法里面即根据传入的 PreparedStatement 执行 查询操作,返回结果。而 PreparedStatement 的获取是在调用回调方法的客户端实现即在execute()方法里面获取,并作为参数传给回调方法。
public Object doInPreparedStatement(PreparedStatement ps) throws SQLException {
ResultSet rs = null;
try {
if (pss != null) {
pss.setValues(ps);
}
if (getFetchSize() > 0) {
ps.setFetchSize(getFetchSize());
}
rs = ps.executeQuery();
ResultSet rsToUse = rs;
if (nativeJdbcExtractor != null) {
rsToUse = nativeJdbcExtractor.getNativeResultSet(rs);
}
return rse.extractData(rsToUse);
}
finally {
JdbcUtils.closeResultSet(rs);
if (pss instanceof ParameterDisposer) {
((ParameterDisposer) pss).cleanupParameters();
}
}
}
});
}
那么在execue()方法里面是怎样回调的呢?下面看看execue()方法:
public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action) {
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);
DataSourceUtils.applyTransactionTimeout(ps, getDataSource());
PreparedStatement psToUse = ps;
if (this.nativeJdbcExtractor != null) {
psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps);
}
Object result = action.doInPreparedStatement(psToUse);
SQLWarning warning = ps.getWarnings();
throwExceptionOnWarningIfNotIgnoringWarnings(warning);
return result;
}
catch (SQLException ex) {
throw getExceptionTranslator().translate(
"executing PreparedStatementCallback [" + psc + "]", getSql(psc), ex);
}
finally {
if (psc instanceof ParameterDisposer) {
((ParameterDisposer) psc).cleanupParameters();
}
JdbcUtils.closeStatement(ps);
DataSourceUtils.closeConnectionIfNecessary(con, getDataSource());
}
}
添加删除的操作类似,只是他们的实现都在以execute命名的方法里面。
public void execute(final String sql) throws DataAccessException {
if (logger.isDebugEnabled()) {
logger.debug("Executing SQL statement [" + sql + "]");
}
class ExecuteStatementCallback implements StatementCallback, SqlProvider {
public Object doInStatement(Statement stmt) throws SQLException {
stmt.execute(sql);
return null;
}
public String getSql() {
return sql;
}
}
execute(new ExecuteStatementCallback());
}
public Object execute(final StatementCallback action) {
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();
DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
Statement stmtToUse = stmt;
if (this.nativeJdbcExtractor != null) {
stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
}
Object result = action.doInStatement(stmtToUse);
SQLWarning warning = stmt.getWarnings();
throwExceptionOnWarningIfNotIgnoringWarnings(warning);
return result;
}
catch (SQLException ex) {
throw getExceptionTranslator().translate("executing StatementCallback", getSql(action), ex);
}
finally {
//这里就是我们自己写程序的时候需要写的关于数据库链接的关闭操作
JdbcUtils.closeStatement(stmt);
DataSourceUtils.closeConnectionIfNecessary(con, getDataSource());
}
}
分享到:
相关推荐
代理模式和观察者模式在Spring AOP和事件驱动模型中得到了广泛应用,提供了强大的切面和事件处理能力。策略模式和模板方法模式则分别提供了资源访问的灵活性和统一处理逻辑的框架。最后,责任链模式在Spring的AOP...
设计模式综合运用:主要是笔者在实际工作中运用到的一些设计模式综合运用事例的提炼 Spring设计模式简介:主要是讲述Spring源码中运用到的一些设计模式 Ibatis设计模式简介:主要是讲述Ibatis源码中运用到的一些设计...
Web 应用中模板技术与 JSP 技术的对比 输入验证与数据绑定 异常处理 国际化支持 WebWork2 & Spring Quick Start WebWork 高级特性 Action 驱动模式 XWork 拦截器体系 输入校验 国际化支持 Webwork2...
6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...
6.1 在一般Web应用中访问Spring 209 6.1.1 问题 209 6.1.2 解决方案 210 6.1.3 工作原理 210 6.2 在你的Servlet和过滤器中使用Spring 214 6.2.1 问题 214 6.2.2 解决方案 215 6.2.3 工作原理 215 ...
6.1 在一般Web应用中访问Spring 209 6.1.1 问题 209 6.1.2 解决方案 210 6.1.3 工作原理 210 6.2 在你的Servlet和过滤器中使用Spring 214 6.2.1 问题 214 6.2.2 解决方案 215 6.2.3 工作原理 215 ...
Spring Data MongoDB 2.1中的新特性 5.2。Spring Data MongoDB 2.0中的新特性 5.3。Spring Data MongoDB 1.10中的新特性 5.4。Spring Data MongoDB 1.9中的新特性 5.5。Spring Data MongoDB 1.8中的新特性 5.6。...
Context-support模块:提供了对第三方库嵌入Spring应用的集成支持,比如缓存(EhCache、Guava、JCache)、邮件服务(JavaMail)、任务调度(CommonJ、Quartz)和模板引擎(FreeMarker、JasperReports、速率)。 SpEL模块:...
服务治理 由于Spring Cloud为服务治理做了一层抽象接口,所以在Spring Cloud应用中可以支持多种不同的服务治理框架,比如:Netflix Eureka、Consul、Zookeeper。在Spring Cloud服务治理抽象层的作用下,我们可以无缝...
6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点运算 7.2.3. AspectJ切入点表达式 7.2.4. 便利的切入...
application.properties -> 所有应用程序属性pom.xml 文件 -> 包括所有需要的依赖MVC模型 [M] -> 用户和联系人 [一个用户有多个联系人]在我们的案例中查看 [V] -> 查看页面 [.html] 文件控制器 [C] -> 保存所有需
Kotlin + Spring Boot MVC入门 含电池 Spring Boot 2 MVC 与JVM 8和JVM 11一起使用 准备好使用JdbcTemplate样式的存储库+准备好PostgreSQL设置 ...首先,请确保您在本地PostgreSQL安装中具有quizzy和quiz
使用 JSF、Spring 和 Mybatis 构建 JEE 应用程序的模板 简单的模式 坚持 国际化 JSF 处理异常 构架 JDK 8 Tomcat 8 / 野蝇 8 / 码头 9 Spring IO 平台 1.1.2(JSF 2.2、Spring 4.1、Hibernate 4.3) MyBatis 3.2...
Web应用中模板技术与 JSP技术的对比........................................................47 输入验证与数据绑定............................................................................................
适用人群Java工程师,架构师,Java程序员,JavaWeb学者课程简介1、让初学者从小白开始,善于运用SpringCloud,解脱传统的开发模式的苦恼2、让开发者能够学习更多的开发使用技巧,成为微服务开发大牛〖课程目录〗:1-...
Spring配置管理SessionFactory与数据库的连接,在实际的应用中,数据源会采用依赖注入的方式,传递给SessionFactory。 见beans-config_sh.xml 24.3 Spring对Hibernate的简化 24.3.1 概述 Hibernate的持久层访问步骤...
lombok、log4j2、validation、hutool、commons-lang3、fastjson、poi、knife4j依赖swagger、mysql driver、druid、mybatis及代码生成相关依赖、spring-aop(aspectjweaver)、pagehelper、minio、commons 实现功能...
这些项目旨在展示SSM框架在实际应用中的魅力,同时也为开发者提供了一个快速学习和实践的机会。通过下载和使用这些项目,您将能够深入了解SSM框架的核心概念、设计模式和最佳实践。 二、项目特点 实战性强:这些...