博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mybatis 执行SQL的过程
阅读量:5357 次
发布时间:2019-06-15

本文共 8863 字,大约阅读时间需要 29 分钟。

当我们在调用mybatis mapper的接口时发生了点什么事呢  简单的跟着源码看了看

@Service("userService")  public class UserServiceImpl implements IUserService {      //UserMapper是我的接口,mybatis给它生成一个动态代理    @Resource    private UserMapper userMapper;          public User getUserById(int userId) {          // TODO Auto-generated method stub         //执行我们接口所对应的sql        return this.userMapper.selectByPrimaryKey(userId);      }  }

我们查看一下调用堆栈

我们直接到invoke中看一下发生了什么事

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);    }//查看是否有缓存    final MapperMethod mapperMethod = cachedMapperMethod(method);//继续执行    return mapperMethod.execute(sqlSession, args);  }

我们接着进execute看一下代码

public Object execute(SqlSession sqlSession, Object[] args) {    Object result;    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;      }      case SELECT:        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 {
//把输入参数转换一下 Object param = method.convertArgsToSqlCommandParam(args); //我们查询最后会走到这里 result = sqlSession.selectOne(command.getName(), param); } 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; }

根据我们需求不同  会case到不同的地方,我们跟的是select 所以最后会走到sqlSession.selectOne部分,接着进入代码

public 
T selectOne(String statement, Object parameter) { return this.sqlSessionProxy.
selectOne(statement, parameter); }

我们可以看出sqlSessionProxy也是一个代理对象,它代理的是谁呢,是我们的DefaultSqlSession 我们进入DefaultSqlSession查看

//我们通过动态代理  会走到这里  @Override  public 
T selectOne(String statement, Object parameter) { // Popular vote was to return null on 0 results and throw exception on too many. //然后会调用selectList List
list = this.
selectList(statement, parameter); if (list.size() == 1) { return list.get(0); } else if (list.size() > 1) { throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size()); } else { return null; } }

进入selectList

@Override  public 
List
selectList(String statement, Object parameter, RowBounds rowBounds) { try {//这个是不是特别熟悉,我们在加载xml的时候,会存储到这个里面 MappedStatement ms = configuration.getMappedStatement(statement);//执行sql 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(); } }

我们会通过configuration.getMappedStatement(statement);把xml跟sql相关的 数据取出来,然后我们进入executor.query

@Override  public 
List
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); }
boundSql 中存着的就是我们真实的sql(下图),createCacheKey我猜测是创建查询缓存

然后我们进入query函数

public 
List
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
list = (List
) 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; } } return delegate.
query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); }

我们可以看到,最初是查询缓存,如果没有的话 ,我们又会进入一个query

public 
List
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
list; try { queryStack++; list = resultHandler == null ? (List
) localCache.getObject(key) : null; if (list != null) { handleLocallyCachedOutputParameters(ms, key, parameter, boundSql); } else { //从这进入queryFromDatabase数据库查询 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 
List
queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { List
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; }

我们会先把缓存的key存起来,然后执行doQuery

public 
List
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.
query(stmt, resultHandler); } finally { closeStatement(stmt); } }

获取configuration 之后 执行handler.query

public 
List
query(Statement statement, ResultHandler resultHandler) throws SQLException { return delegate.
query(statement, resultHandler); }
@Override  public 
List
query(Statement statement, ResultHandler resultHandler) throws SQLException { PreparedStatement ps = (PreparedStatement) statement; ps.execute(); return resultSetHandler.
handleResultSets(ps); }

执行到这里  是不是看到jdbc的执行语句了,没错 就是PreparedStatement !

这篇简单的说了一下mybatis的执行过程,如果有不对之处敬请指出,关于xml的加载还有动态代理的问题  请看我其他文章

转载于:https://www.cnblogs.com/to-be-continue/p/8275967.html

你可能感兴趣的文章
OpenLayers绘制图形
查看>>
tp5集合h5 wap和公众号支付
查看>>
Flutter学习笔记(一)
查看>>
iOS10 国行iPhone联网权限问题处理
查看>>
洛谷 P1991 无线通讯网
查看>>
Codeforces Round #178 (Div. 2) B. Shaass and Bookshelf 【动态规划】0-1背包
查看>>
SparkStreaming 源码分析
查看>>
【算法】—— 随机音乐的播放算法
查看>>
mysql asyn 示例
查看>>
数据库第1,2,3范式学习
查看>>
《Linux内核设计与实现》第四章学习笔记
查看>>
使用iperf测试网络性能
查看>>
图片的显示隐藏(两张图片,默认的时候显示第一张,点击的时候显示另一张)...
查看>>
Docker 安装MySQL5.7(三)
查看>>
python 模块 来了 (调包侠 修炼手册一)
查看>>
关于CSS的使用方式
查看>>
分析语句执行步骤并对排出耗时比较多的语句
查看>>
原生JS轮播-各种效果的极简实现
查看>>
计数器方法使用?
查看>>
带你全面了解高级 Java 面试中需要掌握的 JVM 知识点
查看>>