mybatis四大金刚之executor执行器
Posted 我爱看明朝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis四大金刚之executor执行器相关的知识,希望对你有一定的参考价值。
mybatis四大金刚之executor执行器
configuration.newExecutor()所有流程的开始
public class DefaultSqlSession {
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
}
Executor的主流程
mybatis执行器,通过拼接出sql,调用StatementHanlder执行database操作,以及缓存的子类可以重用预处理语句
(本节展示的源码代码,为了帮助同学们,减少干扰理解executor的执行流程省略了一些代码。)
public abstract class BaseExecutor implements Executor{
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
// 省略部分代码
List<E> list;
//从db查询
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
return list;
}
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
// doQuery方法的具体实现在BaseExecutor的子类,这里使用了模板方法的设计模式:
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
return list;
}
模板方法: 父类封装整个算法步骤,将某些步骤延迟到子类实现,使得不需要改变算法结构的情况下,重新定义算法中的某些步骤
默认的执行器SimpleExecutor
来看看怎么选的默认处理器
public enum ExecutorType {
SIMPLE, REUSE, BATCH
}
public class Configuration{
//默认值
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
//根据executorTypec返回Executor的子类
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
//默认的执行器
executor = new SimpleExecutor(this, transaction);
}
// 使用二级缓存
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
}
简单的执行器,根据对应sql拼接完成后,直接交给StatementHanlder去执行
public class SimpleExecutor extends BaseExecutor{
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
}
执行器的类图
可以看到BaseExecutor实现了Executor; SimpleExecutor,ReuseExecutor,BatchExecutor继承了BaseExecutor,
把具体的操作细节方法: doUpdate、doFlushStatements、doQuery、doQueryCursor通过模板方法交给不同的子类实现的。
SimpleExecutor : 简单的执行器
ReuseExecutor : 可重用执行器
BatchExecutor : 批处理执行器
那CachingExecutor这个类是做什么用的呢,我们在后面通过阅读源码同学们就知道具体是做什么的了,我们单单看累的名字记住它是一个缓存执行器。
ReuseExecutor可重用执行器
看名字,我们就知道这个处理器的作用是重复执行,如果已经在当前线程生命周期内查询过了,不需要在重新创建Statement了。我们直接看它的doquery方法,因为它的逻辑和simpleExecutor的区别就在doQuery这几个方法
public class ReuseExecutor extends BaseExecutor {
//存储未预编译的sql于带 "?"
private final Map<String, Statement> statementMap = new HashMap<String, Statement>();
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
Statement stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
}
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
BoundSql boundSql = handler.getBoundSql();
String sql = boundSql.getSql();
if (hasStatementFor(sql)) {
//如果当前线程存在sql,则获取到map存储的,不需要在创建了
stmt = getStatement(sql);
applyTransactionTimeout(stmt);
} else {
//没有则创建,并且缓存到map中
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
putStatement(sql, stmt);
}
handler.parameterize(stmt);
return stmt;
}
private Statement getStatement(String s) {
return statementMap.get(s);
}
private void putStatement(String sql, Statement stmt) {
statementMap.put(sql, stmt);
}
}
注意这里的缓存仅在当前线程内有效。
如何开启的mybatis.xml配置方式是
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration 核心配置文件 -->
<configuration>
<settings>
<setting name="defaultExecutorType" value="REUSE"/>
</settings>
</configuration>
BatchExecutor
批量执行,只对修改操作生效,对查询不生效,只对当前线程中的同修改sql,可以直接复用之前的statement,
使用这个处理器时要和doFlushStatements、commit方法一起使用,当执行commit数据写入数据库
public class BatchExecutor extends BaseExecutor {
private final List<BatchResult> batchResultList = new ArrayList<BatchResult>();
private String currentSql;
private MappedStatement currentStatement;
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
final Configuration configuration = ms.getConfiguration();
final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
final BoundSql boundSql = handler.getBoundSql();
final String sql = boundSql.getSql();
final Statement stmt;
// 如果sql存在使用之前的statement
if (sql.equals(currentSql) && ms.equals(currentStatement)) {
int last = statementList.size() - 1;
stmt = statementList.get(last);
applyTransactionTimeout(stmt);
handler.parameterize(stmt);//fix Issues 322
BatchResult batchResult = batchResultList.get(last);
batchResult.addParameterObject(parameterObject);
} else {
Connection connection = getConnection(ms.getStatementLog());
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt); //fix Issues 322
currentSql = sql;
currentStatement = ms;
statementList.add(stmt);
batchResultList.add(new BatchResult(ms, sql, parameterObject));
}
// handler.parameterize(stmt);
handler.batch(stmt);
return BATCH_UPDATE_RETURN_VALUE;
}
}
BatchExecutor和ReuseExecutor很像区别就在于,ReuseExecutor复用了直接操作数据库,而batch则是最后一起提交写入数据库,可以节省网络通信时间。
如何开启的mybatis.xml配置方式是
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration 核心配置文件 -->
<configuration>
<settings>
<setting name="defaultExecutorType" value="BATCH"/>
</settings>
</configuration>
CachingExecutor
CachingExecutor表示启动二级缓存,默认开启。
public class Configuration{
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
//根据配置或默认值创建SimpleExecutor、ReuseExecutor、BatchExecutor执行器
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
//缓存默认开启,创建CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
如何安装LAMP四大金刚之“AMP”,文末附论坛创建步骤