文章目录
一、主干代码和源码
接着上篇,本篇研究mybatis如何获取执行器并执行解析后的sql
1.1 主干代码1
SqlSession sqlSession = sqlSessionFactory.openSession();
1.2主干源码1
DefaultSqlSessionFactory类:
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
//获取前面解析赋值的environment
final Environment environment = configuration.getEnvironment();
//获取事务工厂
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//获取执行器-因没有执行执行器类型,按默认的--下面详细解析
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
2.1主干代码2
//此步比较简单,就是动态代理,后面不做详解了。看一下下面的源码就Ok了
MyMapper mapper = sqlSession.getMapper(MyMapper.class);
2.2主干源码2
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//这一步简单,就是通过下面的代码将之前注册到Configuration的MapperRegistry 中的mappper获取到
//Configuration:protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
return mapperRegistry.getMapper(type, sqlSession);
}
mapperRegistry:最终就是通过动态代理获取到mapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
mapperProxyFactory:
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
3.1 主干代码3
//执行sql并封装结果集
List<MyBean> myBeans = mapper.selectOne(1);
3.2主干源码3:后面详解
二、源码分析
1.1分析主干源码1-执行器创建
获取environment就是把之前解析获取的信息取出来。
主要看一下后两步
创建执行器:
//根据设定的执行器类型和事务设置创建执行器
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
//判断是否设定执行器类型,没有就是使用默认执行器SIMPLE
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;
}
1.2分析主干源码1-创建DefaultSqlSession
使用前面的configuration(各属性,eg:environment)、执行器
构建DefaultSqlSession多态形式返回SqlSession
public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
this.configuration = configuration;
this.executor = executor;
this.dirty = false;
this.autoCommit = autoCommit;
}
2.1 分析主干代码3
List myBeans = mapper.selectOne(1);
public interface MyMapper {
@Select("select * from MyBean where id = #{id}")
List<MyBean> selectOne(int p);
}
追踪到这,无法追踪代码了,就需要逆推代码执行流程。
2.1.1逆推代码执行流程
因为sql都是最终由mybatis执行器执行的,而执行器顶层接口Executor;
BaseExecutor执行器实现顶层接口,三大执行器实现BaseExecutor。
执行器的关系如图:

所有执行器都是实现的BaseExecutor,执行本次查询时,在所有关于query的方法打断点,来获取栈调用,逆推源码执行。最终找到调用的是query方法。

2.1.2 栈调用:
query:142, BaseExecutor (org.apache.ibatis.executor)
query:109, CachingExecutor (org.apache.ibatis.executor)
query:89, CachingExecutor (org.apache.ibatis.executor)
selectList:148, DefaultSqlSession (org.apache.ibatis.session.defaults)
selectList:141, DefaultSqlSession (org.apache.ibatis.session.defaults)
executeForMany:147, MapperMethod (org.apache.ibatis.binding)
execute:80, MapperMethod (org.apache.ibatis.binding)
invoke:144, MapperProxy$PlainMethodInvoker (org.apache.ibatis.binding)
invoke:85, MapperProxy (org.apache.ibatis.binding)
selectOne:-1, $Proxy5 (com.sun.proxy)
main:46, MybatisMain (com.study.anno)
根据调用栈,进行跟踪代码执行流程。
2.2 源码分析3
执行到mapper接口的List selectOne(int p);方法后,会到MapperProxy通过动态代理进行执行sql:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
//获取方法的方法名和类型,并执行该方法
return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
判断方法类型和返回类型,来决定调用具体的哪个底层方法:
本次是select的查询
MapperMethod源码:
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
//返回结果是list,因此调用该方法
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
//查询单个最终调用这里
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional()
&& (result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
result = executeForMany(sqlSession, args);
private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
List<E> result;
//获取参数并将参数转成sql里面要的参数
Object param = method.convertArgsToSqlCommandParam(args);
if (method.hasRowBounds()) {
//分页查询
RowBounds rowBounds = method.extractRowBounds(args);
result = sqlSession.selectList(command.getName(), param, rowBounds);
} else {
//调用DefaultSqlSession的selectList方法
result = sqlSession.selectList(command.getName(), param);
}
//对查询出来的结果进行判断,是否出现的结果类型和方法要求的类型
if (!method.getReturnType().isAssignableFrom(result.getClass())) {
if (method.getReturnType().isArray()) {
return convertToArray(result);
} else {
return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
}
}
return result;
}
DefaultSqlSession
@Override
public <E> List<E> selectList(String statement, Object parameter) {
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {//statement:com.study.mapper.MyMapper.selectOne
//根据statement的id获取之前放到Configuration.mappedStatements这个map中的MappedStatement
MappedStatement ms = configuration.getMappedStatement(statement);
//执行器执行MappedStatement
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();
}
}
1 缓存:
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
//获取要执行的sql
BoundSql boundSql = ms.getBoundSql(parameterObject);
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
//先查询缓存
Cache cache = ms.getCache();
if (cache != null) {//如果有缓存
flushCacheIfRequired(ms);//清除缓存
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
//执行查询:下面进行详解
list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
//如果使用缓存,就将查询的结果放到缓存中
tcm.putObject(cache, key, list);
}
return list;
}
} //执行查询:下面进行详解
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
2 执行查询:通过调用baseExecutor的query,来调用默认的simpleExecutor的doquery方法:
@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,负责操作 Statement 对象与数据库进行交流
//详解见 3 处理器初始化
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//初始化Statement 下面详解见4 初始化Statement具体步骤:
stmt = prepareStatement(handler, ms.getStatementLog());
//执行sql获取结果 下面详解见5、PreparedStatementHandler执行sql:
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
3 处理器初始化
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
初始化源码:
configuration类
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
创建路由StatementHandler:
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
//根据获取到的类型决定路由到哪个处理器
switch (ms.getStatementType()) {
case STATEMENT://执行简单的sql-没有参数需要预编译的sql
//eg: select * from tb_user;
delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case PREPARED://有参数要预编译
// select * from tb_user where id = #{id};
delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
case CALLABLE://跑存储过程的
delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
break;
default:
throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
}
}
最终调用父类初始化方法:
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
this.configuration = mappedStatement.getConfiguration();
this.executor = executor;
this.mappedStatement = mappedStatement;
this.rowBounds = rowBounds;
this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
this.objectFactory = configuration.getObjectFactory();
if (boundSql == null) { // issue #435, get the key before calculating the statement
generateKeys(parameterObject);
boundSql = mappedStatement.getBoundSql(parameterObject);
}
this.boundSql = boundSql;
//初始化参数处理器,并将处理器放到interceptorChain
this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
//初始化结果处理器,并将处理器放到interceptorChain
this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
初始化参数和结果处理器源码:
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
最终返回的初始化的处理器:

4 初始化Statement具体步骤:
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
//与数据库建立连接
Connection connection = getConnection(statementLog);
//创建Statement对象实例-初始化 Statement 对象
stmt = handler.prepare(connection, transaction.getTimeout());
//对参数进行初始化
handler.parameterize(stmt);
return stmt;
}
创建Ststement:
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
ErrorContext.instance().sql(boundSql.getSql());
Statement statement = null;
try {
//初始化:也是通过路由的方式来决定调用哪种statement
statement = instantiateStatement(connection);
//设置超时
setStatementTimeout(statement, transactionTimeout);
//设置jdbc读缓存的大小-每次读的条数
//http://ifeve.com/mybatis%e4%b8%ad%e4%bd%bf%e7%94%a8%e6%b5%81%e5%bc%8f%e6%9f%a5%e8%af%a2%e9%81%bf%e5%85%8d%e6%95%b0%e6%8d%ae%e9%87%8f%e8%bf%87%e5%a4%a7%e5%af%bc%e8%87%b4oom/
setFetchSize(statement);
return statement;
} catch (SQLException e) {
closeStatement(statement);
throw e;
} catch (Exception e) {
closeStatement(statement);
throw new ExecutorException("Error preparing statement. Cause: " + e, e);
}
}
//org.apache.ibatis.executor.statement.PreparedStatementHandler:
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() == ResultSetType.DEFAULT) {//创建PreparedStatement
return connection.prepareStatement(sql);
} else {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
}
}
初始化Ststement:
handler.parameterize(stmt);
也是通过RoutingStatementHandler路由,然后由PreparedStatementHandler(因为本次的sql是有参数需要预编译的)来进行参数初始化。
public void parameterize(Statement statement) throws SQLException {
parameterHandler.setParameters((PreparedStatement) statement);
}
具体的参数初始化:parameterHandler设置参数
获取每一个参数的值进行设置。这些参数信息都是从一个大map中获取,每个statement对应一个小map,小map里是一个个参数对应一个个的值
//PreparedStatement :{com.mysql.cj.jdbc.ClientPreparedStatement:
// select * from Blog where id = 2}
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;//本次在此对参数id进行赋值为2
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
//对参数的其他属性进行初始化
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException | SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
5、PreparedStatementHandler执行sql:
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
return resultSetHandler.handleResultSets(ps);
}
5.1resultSetHandler接口-实现类DefaultResultSetHandler来实际处理结果集
public List<Object> handleResultSets(Statement stmt) throws SQLException {
ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
ResultSetWrapper rsw = getFirstResultSet(stmt);
//结果集中包含有之前初始化时,存放的类的className每个字段的类型(String,int),结果类(mybean),在数据库中的对应的jdbcType字段类型(INTEGER,VARCHAR)
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int resultMapCount = resultMaps.size();
validateResultMapsCount(rsw, resultMapCount);
while (rsw != null && resultMapCount > resultSetCount) {
ResultMap resultMap = resultMaps.get(resultSetCount);
//获取结果类型并处理结果集:详解见下面
handleResultSet(rsw, resultMap, multipleResults, null);
rsw = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
//获取结果类型并处理结果集
private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
try {
if (parentMapping != null) {
handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
} else {
if (resultHandler == null) {
//获取到默认的handler
DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
//处理结果:见下面的最终调用
handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
multipleResults.add(defaultResultHandler.getResultList());
} else {
handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
}
}
} finally {
// issue #228 (close resultsets)
closeResultSet(rsw.getResultSet());
}
}
5.2获取结果的类型,并将结果封装进对象
还是DefaultResultSetHandler类中:
private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
throws SQLException {
DefaultResultContext<Object> resultContext = new DefaultResultContext<>();
ResultSet resultSet = rsw.getResultSet();
skipRows(resultSet, rowBounds);
while (shouldProcessMoreRows(resultContext, rowBounds) && !resultSet.isClosed() && resultSet.next()) {
//获取到配置的结果集类型:Mybean的类型
ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(resultSet, resultMap, null);
//将结果封装进行Mybean对象中 rowValue 现在已经是mybean对象了
Object rowValue = getRowValue(rsw, discriminatedResultMap, null);
storeObject(resultHandler, resultContext, rowValue, parentMapping, resultSet);
}
}
2.3总结:
查询的方法被调用后,先到缓存中查询,是否有缓存,有缓存就先清除,然后调用base执行器,来执行query–》queryFromDatabase,最终已前面创建的执行器来实现base执行器的doquery方法,该方法就是将之前赋值好的Configuration,创建对应的StatementHandler,执行器最终还是交给handler来处理sql。先是交给PreparedStatementHandler执行sql获取结果,最终调用DefaultResultSetHandler 来处理结果集。
大量使用的路由思想,在项目中也可以借鉴,对不同种类的,由统一路由接受,再通过switch 来已枚举的形式进行路由。
附录:MapperMethod的两个属性:
private final SqlCommand command;
private final MethodSignature method;
command:此次的值为
{
name:com.study.mapper.MyMapper.selectOne
type:SELECT
}
MethodSignature method:
{
returnsMany :true
returnsMap :false
returnsVoid :false
returnsCursor :false
returnsOptional :false
returnType :返回的类型,结果类型是否有注解等等
mapKey :null
resultHandlerIndex :null
rowBoundsIndex :null
paramNameResolver :参数实体类,参数类型,是否有参数注解等等
}
2、最终调用栈:
handleRowValuesForSimpleResultMap:353, DefaultResultSetHandler (org.apache.ibatis.executor.resultset)
handleRowValues:328, DefaultResultSetHandler (org.apache.ibatis.executor.resultset)
handleResultSet:301, DefaultResultSetHandler (org.apache.ibatis.executor.resultset)
handleResultSets:194, DefaultResultSetHandler (org.apache.ibatis.executor.resultset)
query:65, PreparedStatementHandler (org.apache.ibatis.executor.statement)
query:79, RoutingStatementHandler (org.apache.ibatis.executor.statement)
doQuery:63, SimpleExecutor (org.apache.ibatis.executor)
queryFromDatabase:325, BaseExecutor (org.apache.ibatis.executor)
query:156, BaseExecutor (org.apache.ibatis.executor)
query:109, CachingExecutor (org.apache.ibatis.executor)
query:89, CachingExecutor (org.apache.ibatis.executor)
selectList:148, DefaultSqlSession (org.apache.ibatis.session.defaults)
selectList:141, DefaultSqlSession (org.apache.ibatis.session.defaults)
executeForMany:147, MapperMethod (org.apache.ibatis.binding)
execute:80, MapperMethod (org.apache.ibatis.binding)
invoke:144, MapperProxy$PlainMethodInvoker (org.apache.ibatis.binding)
invoke:85, MapperProxy (org.apache.ibatis.binding)
selectOne:-1, $Proxy5 (com.sun.proxy)
main:46, MybatisMain (com.study.anno)
文中涉及的四大核心接口对象
执行器Executor:
执行器负责整个SQL执行过程的总体控制。
参数处理器ParameterHandler:
参数处理器负责PreparedStatement入参的具体设置。
语句处理器StatementHandler:
语句处理器负责和JDBC层具体交互,包括prepare语句,执行语句,以及调用ParameterHandler.parameterize()设置参数。
结果集处理器ResultSetHandler:
结果处理器负责将JDBC查询结果映射到java对象。
254




被折叠的 条评论
为什么被折叠?



