资讯专栏INFORMATION COLUMN

MyBatis 源码解析(二):SqlSession 执行流程

Dionysus_go / 430人阅读

摘要:简介上一篇文章源码解析一初始化和动态代理分析了解析配置文件以及动态代理相关的源码,这一篇接着上一篇探究的执行流程,另外了解一下中的缓存。总结本文主要分析了的执行流程,结合上一篇文章基本了解了的运行原理。

简介

上一篇文章(MyBatis 源码解析(一):初始化和动态代理)分析了 MyBatis 解析配置文件以及 Mapper 动态代理相关的源码,这一篇接着上一篇探究 SqlSession 的执行流程,另外了解一下 MyBatis 中的缓存。

openSession

MyBatis 在解析完配置文件后生成了一个 DefaultSqlSessionFactory 对象,后续执行 SQL 请求的时候都是调用其 openSession 方法获得 SqlSessison,相当于一个 SQL 会话。 SqlSession 提供了操作数据库的一些方法,如 selectupdate 等。

先看一下 DefaultSqlSessionFactoryopenSession 的代码:

  public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

  private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      // 从 configuration 取出配置
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      // 每个 SqlSession 都有一个多带带的 Executor 对象
      final Executor executor = configuration.newExecutor(tx, execType, autoCommit);
      // 返回 DefaultSqlSession 对象
      return new DefaultSqlSession(configuration, executor);
    } 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();
    }
  }

主要代码在 openSessionFromDataSource,首先是从 Configuration 中取出相关的配置,生成 Transaction,接着又创建了一个 Executor,最后返回了 DefaultSqlSession 对象。

这里的 Executor 是什么呢?它其实是一个执行器,SqlSession 的操作会交给 Executor 去执行。MyBatis 的 Executor 常用的有以下几种:

SimpleExecutor: 默认的 Executor,每个 SQL 执行时都会创建新的 Statement

ResuseExecutor: 相同的 SQL 会复用 Statement

BatchExecutor: 用于批处理的 Executor

CachingExecutor: 可缓存数据的 Executor,用代理模式包装了其它类型的 Executor

了解了 Executor 的类型后,看一下 configuration.newExecutor(tx, execType, autoCommit) 的代码:

  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    // 默认是 SimpleExecutor
    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;
  }

MyBatis 默认启用一级缓存,即同一个 SqlSession 会共用同一个缓存,上面代码最终返回的是 CachingExecutor

getMapper

在创建了 SqlSession 之后,下一步是生成 Mapper 接口的代理类,代码如下:

 public  T getMapper(Class type) {
    return configuration.getMapper(type, this);
  }

可以看出是从 configuration 中取得 Mapper,最终调用了 MapperProxyFactorynewInstanceMapperProxyFactory 在上一篇文章已经分析过,它是为了给 Mapper 接口生成代理类,其中关键的拦截逻辑在 MapperProxy 中,下面是其 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);
    }
    // 从缓存中获取 MapperMethod 然后调用
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

MapperProxy 中调用了 MapperMethodexecute,下面是部分代码:

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;
      ...
}

可以看出,最终调用了 SqlSession 的对应方法,也就是 DefaultSqlSession 中的方法。

select

先看一下 DefaultSqlSessionselect 的代码:

  public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      executor.query(ms, wrapCollection(parameter), rowBounds, handler);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

select 中调用了 executorquery,上面提到,默认的 ExecutorCachingExecutor,看其中的代码:

  @Override
  public  List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 获取缓存的key
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
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, 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,默认是 SimpleExecutorExecutor 是一个接口,下面有个实现类是 BaseExecutor,其中实现了其它 Executor 通用的一些逻辑,包括 doQuery 以及 doUpdate 等,其中封装了 JDBC 的相关操作。

update

update 的执行与 select 类似, 都是从 CachingExecutor 开始,看代码:

  @Override
  public int update(MappedStatement ms, Object parameterObject) throws SQLException {
    // 检查是否需要刷新缓存
    flushCacheIfRequired(ms);
    // 调用代理类的 update
    return delegate.update(ms, parameterObject);
  }

update 会使得缓存的失效,所以第一步是检查是否需要刷新缓存,接下来再交给代理类去执行真正的数据库更新操作。

总结

本文主要分析了 SqlSession 的执行流程,结合上一篇文章基本了解了 MyBatis 的运行原理。对于 MyBatis 的源码,还有很多地方没有深入,例如SQL 解析时参数的处理、一级缓存与二级缓存的处理逻辑等,不过在熟悉 MyBatis 的整体框架之后,这些细节可以在需要用到的时候继续学习。

如果我的文章对您有帮助,不妨点个赞支持一下(^_^)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72760.html

相关文章

  • Mybatis源码分析

    摘要:我认为学习框架源码分为两步抓住主线,掌握框架的原理和流程理解了处理思路之后,再去理解面向对象思想和设计模式的用法目前第一步尚有问题,需要多走几遍源码,加深下理解,一起加油 这篇文章我们来深入阅读下Mybatis的源码,希望以后可以对底层框架不那么畏惧,学习框架设计中好的思想; 架构原理 架构图 showImg(https://segmentfault.com/img/remote/...

    lindroid 评论0 收藏0
  • MyBatis 源码解析(一):初始化和动态代理

    摘要:最终解析出的和依然是设置到中。到这里,初始化部分就结束了。总结的初始化流程主要是解析配置文件,将相关信息保存在中,同时对每个代表的生成代理对象工厂。 简介 MyBatis 是 Java 开发中非常流行的 ORM 框架,其封装了 JDBC 并且解决了 Java 对象与输入参数和结果集的映射,同时又能够让用户方便地手写 SQL 语句。MyBatis 的行为类似于以下几行代码: Class....

    娣辩孩 评论0 收藏0
  • MyBatis理解与掌握(原理分析)

    摘要:理解与掌握原理分析框架功能架构接口层提供给外部使用的接口,开发人员通过这些本地来操作数据库。流程分析数据处理过程根据的查找相应的对象。预处理对象,得到对象。传入和结果处理对象,通过的方法来执行,并对执行结果进行处理。 MyBatis理解与掌握(原理分析) @(MyBatis)[Java, 框架, MyBatis] 功能架构 showImg(https://segmentfault.co...

    keelii 评论0 收藏0
  • Mybatis是怎么工作的(

    摘要:目标理清加载解析文件的过程理清执行的过程。先看源码生成解析配置文件考虑到项目的配置,看下生成和的代码。在生成的过程中,使用了,这个类继承了。在该类的构造器中加载了和。下面看一下代码从缓存中获取对象执行下面是方法至此,执行完成。 目标: 理清mybatis加载解析mapper文件的过程; 理清mybatis执行SQL的过程。 上一篇文章分析mybatis加载配置的源码时提到了org....

    paulli3 评论0 收藏0
  • Mybatis系列】从源码角度深度理解Mybatis的缓存特性

    摘要:一级缓存介绍及相关配置。在这个章节,我们学习如何使用的一级缓存。一级缓存实验配置完毕后,通过实验的方式了解一级缓存的效果。源码分析了解具体的工作流程后,我们队查询相关的核心类和一级缓存的源码进行走读。 我,后端Java工程师,现在美团点评工作。爱健身,爱技术,也喜欢写点文字。个人网站: http://kailuncen.me公众号: KailunTalk (凯伦说) 前言 本文主要涉及...

    Ku_Andrew 评论0 收藏0

发表评论

0条评论

Dionysus_go

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<