文章目录
MyBatis源码剖析
客户端调用MyBatis接口有两种方式:
- 基于StatementId
- 基于Mapper接口
// 1.Resources工具类,配置文件的加载,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 2.解析了配置文件,并创建了sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 3.生成sqlSession (默认开启一个事务,但是该事务不会自动提交, 参数为true为自动提交)
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 基于StatementId
List<User> userList = sqlSession.selectList("com.demo.mapper.UserMapper.findAll");
// 基于Mapper接口
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.findAll();
基于StatementId方式源码剖析
初始化
// 1.Resources工具类,配置文件的加载,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 2.解析了配置文件,并创建了sqlSessionFactory
// 这一行代码正是初始化工作的开始
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
进入build源码分析
// 1.我们最初调用的build
public SqlSessionFactory build(InputStream inputStream) {
// 调用了重载方法
return build(inputStream, null, null);
}
// 2.调用的重载方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
// XMLConfigBuilder是专门解析MyBatis的配置文件的类
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// 这里又调用了一个重载方法。parser.parse()返回的是Configuration对象
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
}
...
}
MyBatis在初始化的时候,会将MyBatis的配置信息全部加载到内存中,使用 org.apache.ibatis.session.Configuration
实例来维护
配置文件解析部分
首先对Configuration 对象进行介绍
Configuration 对象的结构和xml配置文件的对象几乎相同
回顾下xml中的配置标签有哪些:
properties:属性,settings:设置,typeAliases:类型别名,typeHandlers:类型处理器,objectFactory:对象工厂,mappers:映射器 等
也就是说,初始化配置文件信息的本质就是创建Configuration 对象,将解析的xml数据封装到Configuration 内部属性中
在XMLConfigBuilder中:
/**
* 解析xml成Configuration 对象
*/
public Configuration parse() {
// 如果已经解析,抛出异常
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
// 标记已解析
parsed = true;
// 解析xml configuration 节点
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
// 解析对应的标签
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
MappedStatement
MappedStatement的作用:MappedStatement与Mapper配置文件中的一个节点相对应。
mapper中配置的标签都被封装到了此对象中,主要用途是描述一条sql语句。
初始化过程:回顾刚开始介绍的加载配置文件的过程中,会对 sqlMapConfig.xml
文件中的各个标签进行解析,其中有mappers标签用来引入mapper.xml文件或者配置mapper接口的目录
<select id="findAll" resultType="user">
select * from user
</select>
这样的一个select标签会在初始化配置文件时被解析封装成一个MappedStatement对象,然后存储在Configuration对象的mappedStatements属性中,mappedStatements 是一个HashMap,存储时key = 全限定类名 + 方法名,value = 对应的MappedStatement对象
-
在configuration 中对应的属性为
Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
-
在XMLConfigBuilder 中的处理
private void parseConfiguration(XNode root) { try { ... mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } }
到此对xml配置文件的解析就结束了 ,回到 进入build源码分析 中调用build方法
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
执行SQL流程
初始化完毕之后,我们就要执行sql了
// 3.生成sqlSession (默认开启一个事务,但是该事务不会自动提交, 参数为true为自动提交)
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 基于StatementId
List<User> userList = sqlSession.selectList("com.demo.mapper.UserMapper.findAll");
SqlSession介绍
先简单介绍下SqlSession,SqlSession是一个接口,它有两个实现类:DefaultSqlSession(默认)和SqlSessionManager(弃用)
SqlSession是MyBatis中用于和数据库交互的顶层类,通常将它与ThreadLocal绑定,一个会话使用一个SqlSession,并且在使用完毕后需要close
public class DefaultSqlSession implements SqlSession {
private final Configuration configuration;
private final Executor executor;
...
}
SqlSession 中的两个最重要的参数,configuration与初始化时的相同,Executor为执行器
-
Executor
Executor也是一个接口,它有三个常用的实现类:
BatchExecutor (重用语句并执行批量操作)
ReuseExecutor(重用预处理语句prepared statement)
SimpleExecutor (普通的执行器,默认)
获得SqlSession
进入到openSession方法
@Override
public SqlSession openSession() {
// getDefaultExecutorType() 传递的是SimpleExecutor
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
进入到openSessionFromDataSource方法
/**
* 开启一个SqlSession
* @param execType 为Executor的类型
* @param level 事务隔离级别
* @param autoCommit 是否开启事务
* @return
*/
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 根据参数创建指定类型的Executor
final Executor executor = configuration.newExecutor(tx, execType);
// 返回的是DefaultSqlSession
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();
}
}
执行SqlSession中的API
// selectList方法有多个重载方法
@Override
public <E> List<E> selectList(String statement) {
return this.selectList(statement, null);
}
@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 Id充映射的Map中取出MappedStateMent对象
MappedStatement ms = configuration.getMappedStatement(statement);
// 调用Executor中的方法处理 rowBounds是用来逻辑分页 wrapCollection(parameter)是用来装饰集合或者数组参数
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
进入Executor执行器后,进入executor.query方法,该方法在SimpleExecutor的父类BaseExecutor中实现
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
// 根据传入参数动态获得SQL语句,最后返回用BoundSql对象表示
BoundSql boundSql = ms.getBoundSql(parameter);
// 为此次查询创建缓存的Key
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
// 进入下面的query的重载方法中
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
@SuppressWarnings("unchecked")
@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());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 如果缓存中没有本次查找的值,那么从数据库中查询
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
从数据库查询
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
// 查询的方法
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
// 将查询结果放入缓存中
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
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对象来执行查询
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
// 创建JDBC中的statement对象
stmt = prepareStatement(handler, ms.getStatementLog());
// StatementHanlder进行处理
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
...
/**
* 创建Statement方法
*/
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
// getConnection方法会经过重重调用最后调用openConnection方法,从连接池中获得连接
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
handler.parameterize(stmt);
return stmt;
}
/**
* 从连接池获得连接的方法
*/
protected void openConnection() throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Opening JDBC Connection");
}
// 从连接池获得连接
connection = dataSource.getConnection();
if (level != null) {
connection.setTransactionIsolation(level.getLevel());
}
setDesiredAutoCommit(autoCommit);
}
上述Executor.query()方法几经转折,最后会创建一个StatementHandler对象,然后将必要的参数传递给StatementHandler,使用StatementHandler来完成对数据库的查询,最终返回List结果集。
从上面代码中我们可以看出,Executor的功能和作用是:
- 根据传递的参数,完成对SQL语句的动态解析,生成BoundSql对象,供StatementHandler使用
- 为查询创建缓存,以提高性能
- 创建JDBC的Statement连接对象,传递给StatementHandler对象,返回List结果
StatementHandler
StatementHandler对象主要完成两个工作:
- 对于JDBC的PreparedStatement类型的对象,创建的过程中,我们使用的是SQL语句字符串,会包含若干个?占位符,我们其后再对占位符进行设值。StatementHandler通过parameterize(statement) 方法对Statement进行设值。
- StatementHandler通过List query(Statement statement, ResultHandler resultHandler) 方法来完成执行Statement,和将Statement对象返回的resultSet 封装成List
进入到StatementHandler的parameterize(statement) 方法的实现:
在org.apache.ibatis.executor.statement.PreparedStatementHandler中
@Override
public void parameterize(Statement statement) throws SQLException {
// 使用ParameterHandler对象完成对Statement的设值
parameterHandler.setParameters((PreparedStatement) statement);
}
/**
* ParameterHandler类的setParameters 实现对某一个Statement进行设置参数
*/
@Override
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;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
// 每一个Mapping都有一个TypeHandler,根据TypeHandler来对preparedStatement进行设置参数
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);
}
}
}
}
}
从上述的代码可以看到,StatementHandler 的parameterize(Statement) 方法调用了ParameterHandler的setParameters(statement) 方法,ParameterHandler的setParameters(Statement)方法根据我们输入的参数,对statement对象?占位符处进行赋值。
进入到StatementHandler的List query(Statement statement, ResultHandler resultHandler)方法的实现:
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
// 1.调用preparedStatement.execute()方法,然后将resultSet交给ResultSetHandler处理
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
// 2.使用ResultHandler来处理ResultSet
return resultSetHandler.handleResultSets(ps);
}
从上述代码我们可以看出,StatementHandler的query方法的实现,是调用了ResultSetHandler的handleResultSets(Statement) 方法。handleResultSets方法会将语句执行后生成的resultSet结果集转换成List结果集
@Override
public List<Object> handleResultSets(Statement stmt) throws SQLException {
ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
// 多Resultset 的结果集合,每个ResultSet对应一个Object对象,实际上每个Object是List<Object>对象
// 在不考虑存储过程的多ResultSet的情况,普通的查询,实际就一个ResultSet,也就是说multipleResults最多就一个元素
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
// 获得首个ResultSet对象,并封装成ResultSetWrapper对象
ResultSetWrapper rsw = getFirstResultSet(stmt);
// 获得ResultMap数组
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int resultMapCount = resultMaps.size();
validateResultMapsCount(rsw, resultMapCount);
while (rsw != null && resultMapCount > resultSetCount) {
// 获得ResultSet对象
ResultMap resultMap = resultMaps.get(resultSetCount);
// 处理ResultSet,将结果添加到multipleResults
handleResultSet(rsw, resultMap, multipleResults, null);
// 获得下一个ResultSet对象,并封装成ResultSetWrapper 对象
rsw = getNextResultSet(stmt);
// 清理
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
Mapper代理方式
回顾下写法:
// 1.Resources工具类,配置文件的加载,把配置文件加载成字节输入流
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
// 2.解析了配置文件,并创建了sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 3.生成sqlSession (默认开启一个事务,但是该事务不会自动提交, 参数为true为自动提交)
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 基于Mapper接口 这里不再调用SqlSession的API,而是获得了接口对象,调用接口的方法
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.findAll();
思考一个问题,通常的Mapper接口我们都没有实现的方法但却可以使用,这是为什么?
答案就是 动态代理
开始阅读源码前,我们先介绍下MyBatis初始化时对接口的处理:
MapperRegistry是Configuration中的一个属性,它内部维护一个HashMap用于存放mapper接口的工厂类,每个接口对应一个工厂类。mappers中可以配置接口的包路径,或者某个具体的接口类
<!-- 引入映射配置文件 -->
<mappers>
<package name="com.demo.mapper"/>
</mappers>
当解析mappers标签时,它会判断解析到的是mapper配置文件时,会再将对应配置文件中的增删改查标签一一封装成MappedStatement对象,存入mappedStatement中。当判断解析到接口时,会创建此接口对应的MapperProxyFactory对象,存入HashMap中,key = 接口的字节码对象,value = 此接口对应的MapperProxyFactory对象
getMapper
进入SqlSession.getMapper(UserMapper.class)方法中
// DefaultSqlSession 中的getMapper
@Override
public <T> T getMapper(Class<T> type) {
return configuration.getMapper(type, this);
}
// Configuration 中的getMapper
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
// MapperRegistry 中的getMapper
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// 从MapperRegistry中的HashMap中拿MapperProxyFactory
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);
}
}
MapperProxy类,实现了InvocationHandler 接口
public class MapperProxy<T> implements InvocationHandler, Serializable {
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
// 构造,传入了SqlSession,说明每个session中的代理对象是不同的
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//如果是 Object 定义的方法,直接调用
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (method.isDefault()) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 获得MapperMethod 对象
final MapperMethod mapperMethod = cachedMapperMethod(method);
// 重点在这:MapperMethod 最终调用了执行的方法
return mapperMethod.execute(sqlSession, args);
}
}
进入MapperMethod.execute()方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
// 判断mapper中的方法类型,最终调用的还是SqlSession中的方法
switch (command.getType()) {
case INSERT: {
// 转换参数
Object param = method.convertArgsToSqlCommandParam(args);
// 执行insert操作 转换rowConu
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
...
case SELECT:
// 无返回值,并且有ResultHandler方法参数,则将查询的结果提交给ResultHandler进行处理
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
// 执行查询 返回列表
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
// 执行查询 返回Map
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
// 执行查询 返回Cursor
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;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
// 返回结果为null,并且返回类型为基本类型,则抛出BindingException异常
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
// 返回结果
return result;
}