Mybatis核心源码分析
一、介绍
mybatis作为一款半自动化数据库持久层框架,提供了完整的JDBC操作,对参数解析,sql预编译,返回值解析,数据库事务
的支持,还有对于session的管理,数据缓存的处理;有xml和注解两种配置方式,几乎屏蔽了JDBC的操作;正式因为这种灵活使
它广受国内互联网公司的青睐;
二、核心类
1.SqlSessionFactoryBuilder
通过读取xml文件流或者创建Configuration类的方式注入mybatis的全局配置文件
new SqlSessionFactoryBuilder().build("xml文件路径")或者new SqlSessionFactoryBuilder().build("configuration类")
返回值为SqlSessionFactory
2.SqlSessionFactory
SqlSession的工厂类,可以返回一个session(数据库会话)
两个具体的实现类DefaultSqlSessionFactory和SqlSessionManager
DefaultSqlSessionFactory:会根据mybatis的配置创建session
//execType是Configuration配置文件中指定的执行器
//level级别(事务的级别,根据数据的事务隔离级别不同)
//autoCommit是否自动提交事务
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);
//根据事务和执行器创建实例
final Executor executor = configuration.newExecutor(tx, execType);
//根据以上条件创建一个session
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();
}
}
SqlSessionManager:会通过ThreadLocal创建session,保证创建的session只有当前线程使用(session本身线程不安全)
这样session的生命周期就会跟随当前线程
3.SqlSession
mybatis提供的操作数据库增删改查的顶层接口,内部有我们配置和具体的执行器
4.Executor
mybatis提供的具体操作数据库的类,增删改查,事务提交,回滚等;有以下四个实现
SimpleExecutor:简单的数据库操作,没有缓存,使用完释放所有资源
BatchExecutor:只提供了增删改的功能,不支持查询操作
ReuseExecutor:对于statement的缓存,用map封装
private void putStatement(String sql, Statement stmt) {
statementMap.put(sql, stmt);
}
CachingExecutor:会对结果查询结果做缓存,如果在同一个缓存中有,那么直接使用缓存
@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, parameterObject, boundSql);
@SuppressWarnings("unchecked")
//如果缓存中有,那么直接返回数据,不再查询数据库
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
5.StatementHandler
对statement对象的操作类,对应也有四个实现,在介绍StatementHandler内容之前先聊以下statement的内容
statement:类路径 java.sql,是具体执行某一个确定的sql,并且返回一个结果;这里的sql是即将传递给数据库执行的语句
有两个实现类prepareStatement和CallableStatement
prepareStatement:预编译好的sql
CallableStatement:预编译好的存储过程
StatementHandler就是对以上Statement的操作,以下为StatementHandler的四个实现类
SimpleStatementHandler:用于处理JDBC中简单的statement接口
CallableStatementHandler:用于处理存储过程的CallableStatement
PrepareStatementHandler:用于处理我们预编译好的PrepareStatement
RoutingStatementHandler:没有实际逻辑,只负责以上三个handler的调度
三、源码跟踪一次请求
简单的mybatis一次完整请求
@Test
public void testGet() throws Exception{
//1创建mybatis的构建器
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2解析具体的xml或者configuration类(配置有数据库连接,mapper文件地址)
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
//3打开一个会话连接
SqlSession session = sqlSessionFactory.openSession();
//4获取mapper的代理对象
WmsUserConfMapper mapper = session.getMapper(WmsUserConfMapper.class);
//5通过代理对象执行具体的sql
mapper.get("a");
}
第一,二,三可以自己跟一下源码,这里不做过多解释,直接从获取mapper代理对象开始
通过上边对session的讲解可知,当前获得是一个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);
}
进入mapper注册,也就是创建代理对象的方法
@SuppressWarnings("unchecked")
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);
}
}
mapper代理对象创建完毕,接下来进入重点,调用代理对象mapper.get("a");方法,我们debug进来,看到invoke方法
@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 if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
//1.缓存mapper的数据,第二次进入相同mapper直接访问缓存,提高效率
final MapperMethod mapperMethod = cachedMapperMethod(method);
//2.执行具体逻辑
return mapperMethod.execute(sqlSession, args);
}
先看下上述代码块中步骤1对应的源码,第一次访问mapper会创建一个mapperMethod,源码如下
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
//根据config配置,接口,和方法,创建当前方法的mapperStatement对象
this.command = new SqlCommand(config, mapperInterface, method);
//根据config配置,接口,和方法,获取当前mapper接口方法对应的签名信息
this.method = new MethodSignature(config, mapperInterface, method);
}
new SqlCommand()和new MethodSignature()源码,可自行跟踪一下,没什么复杂的逻辑
步骤2执行的源码如下
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//1.type是根据解析mapper对应的xml文件标签得到的
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
//2.我们这里是select直接看这块逻辑
case SELECT:
//3.根据方法签名上的返回值决定执行不同的方法
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
//4.我们这里没有返回值,并且返回值没有resultHandler
//5.解析方法上的参数
Object param = method.convertArgsToSqlCommandParam(args);
//6.执行session的查询
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());
}
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;
}
我们跟一下上述5参数解析部分的源码,如下
public Object getNamedParams(Object[] args) {
//当前方法的参数保存在一个有序的map中即names,value为属性名称
final int paramCount = names.size();
//判断names的大小来决定逻辑
if (args == null || paramCount == 0) {
return null;
} else if (!hasParamAnnotation && paramCount == 1) {
return args[names.firstKey()];
} else {
final Map<String, Object> param = new ParamMap<>();
int i = 0;
for (Map.Entry<Integer, String> entry : names.entrySet()) {
//通过循环将属性名称和值存放到map中使用
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, ...)
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
//返回一个map对象
return param;
}
}
上述第6步执行session的查询方法,我们在进入源码,一直走到DefaultSqlSession中,如下
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
//通过配置文件获取mapper中对应的statement的sql语句
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.query方法,我们这里进入的是CachingExecutor类中,源码如下
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
//构建sql,及参数数据,封装为boundSql对象
BoundSql boundSql = ms.getBoundSql(parameterObject);
//创建缓存
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
//执行查询
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
进入query方法,如下
@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); // issue #578 and #116
}
return list;
}
}
//这里真正执行的SimpleExecutor的查询
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
进入delegate.query()方法,这里走到了SimpleExecutor的父类BaseExecutor
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;
}
进入queryFromDataBase方法
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;
}
[点击并拖拽以移动]
进入doQuery方法,到了SimpleExecutor类中
@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);
//通过预编译的方式,构建出完整的sql语句
stmt = prepareStatement(handler, ms.getStatementLog());
//调用到PrepareStatementHandler进行sql的查询操作
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
进入到PrepareStatementHandler进行查询操作,会调用到PrepareStatement的execute执行查询,最终将结果返回,并
用ResultSetHandler处理请求的结果
四、总结
第一次完完整整一步一步的走了一遍mybatis的源码,感觉收货还是蛮大的,一遍debug一遍记录,扫了很多盲点,走完一遍
后发现对于数据库和mybatis这块的内容又有了新的认识,不知不觉过去了三个小时了