一:JdbcTemplate的简介
JdbcTemplate 是 Spring Template设置模式中的一员。类似的还有 TransactionTemplate、 MongoTemplate 等。通过 JdbcTemplate 我们可以使得 Spring 访问数据库的过程简单化。
二:执行SQL语句的方法
1:在JdbcTemplate中执行SQL语句的方法大致分为3类
execute:可以执行所有SQL语句,但是没有返回值。一般用于执行DDL(数据定义语言,主要的命令有CREATE、ALTER、DROP等)语句。
update:用于执行INSERT、UPDATE、DELETE等DML语句。
queryXxx:用于DQL数据查询语句。
2: 基本使用方式如下
JdbcTemplate jdbcTemplate = run.getBean(JdbcTemplate.class);
// 查询
List<User> maps = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
// 更新
int update = jdbcTemplate.update("update user set password = ? where id = 1", "6666");
三:核心方法 - execute
实际上,无论是query 或者 update,其底层调用的都是 JdbcTemplate#execute(org.springframework.jdbc.core.StatementCallback<T>) 方法。
execute:作为数据库操作的核心入口,其实实现逻辑和我们一起最基础的写法类似。将大多数数据库操作对相同的统一封装,而将个性化的操作使用 StatementCallback 进行回调,并进行数据库资源释放的一些收尾操作。
execute 方法的作用是获取数据库连接,准备好Statement, 随后调用预先传入的回调方法。
下面我们直接来看 JdbcTemplate#execute(org.springframework.jdbc.core.StatementCallback<T>) 方法:
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
// 从数据源中获取数据连接
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
// 创建 Statement 。
stmt = con.createStatement();
// 应用一些设置
applyStatementSettings(stmt);
// 回调执行个性化业务
T result = action.doInStatement(stmt);
// 警告处理
handleWarnings(stmt);
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.
// 释放数据库连接,避免当异常转换器没有被初始化的时候出现潜在的连接池死锁
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallb