上两篇已经讲解了SqlSessionFactory的创建和SqlSession创建过程。今天我们来分析myabtis的sql是如何一步一步走到Excutor。

还是之前的demo

   public static void main(String[] args) throws Exception {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        SqlSession sqlSession = sessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(userMapper.findUserById(1));
    }

我们想看下基本的时序图有个大致了解

1:DefaultSqlSession获取getMapper

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

2:Configuration获取getMapper

 public  T getMapper(Class type, SqlSession sqlSession) {
   return mapperRegistry.getMapper(type, sqlSession);
 }

Configuration和DefaultSqlSession什么都没有做,交给了MapperRegistry,我们看下MapperRegistry做了什么。

3:MapperRegistry获取getMapper

 @SuppressWarnings("unchecked")
  public  T getMapper(Class type, SqlSession sqlSession) {
    final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) 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);
    }
  }

通过knownMappers获取一个MapperProxyFactory,后然newInstance了一下,那么newInstance得到了什么东西呢?

4:MapperProxyFactory

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy mapperProxy) {
  //java代理
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

通过以上的动态代理,咱们就可以方便地使用dao接口啦。到这里我们还没有看到任何执行sql有关的信息,或者说还没走到文章开始说的的Excutor, 我们看下MapperProxy代理类

MapperProxy

public class MapperProxy implements InvocationHandler, Serializable {
  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class mapperInterface;
  private final Map methodCache;
  public MapperProxy(SqlSession sqlSession, Class mapperInterface, Map methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
      }
    }
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }
  private MapperMethod cachedMapperMethod(Method method) {
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }
}

代理类交给了mapperMethod.execute进行处理,到这里我们只是看到了execute字眼了,我们继续往下看。

  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    if (SqlCommandType.INSERT == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.insert(command.getName(), param));
    } else if (SqlCommandType.UPDATE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.update(command.getName(), param));
    } else if (SqlCommandType.DELETE == command.getType()) {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = rowCountResult(sqlSession.delete(command.getName(), param));
    } else if (SqlCommandType.SELECT == command.getType()) {
      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);
      }
    } else if (SqlCommandType.FLUSH == command.getType()) {
        result = sqlSession.flushStatements();
    } else {
      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;
  }

上面代码先是判断CRUD类型,然后根据类型去选择到底执行sqlSession中的哪个方法,我们现在是查询那么程序应该走到sqlSession.selectOne。

  @Override
  public  T selectOne(String statement, Object parameter) {
    // Popular vote was to return null on 0 results and throw exception on too many.
    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;
    }
  }
  @Override
  public  List selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      //终于看到我们要找的executor接口了
      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方法,接下来的事情全部交给了executor处理了,

executor底层的分析已经在上一篇已经分享了。

我们代理执行sql的基本顺序是

MapperMethod.execute() --> DefaultSqlSession.selectOne  -->  BaseExecutor.query  -->  SimpleExecutor.doQuery  --> SimpleStatementHandler.query -->  DefaultResultSetHandler.handleResultSets(Statement stmt)  最终得到数据。

Mybatis源码分析之Mapper执行SQL过程(三)的更多相关文章

  1. 精尽 MyBatis 源码分析 - SqlSession 会话与 SQL 执行入口

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  2. mybatis源码分析(五)------------SQL的执行过程

    在对SQL的执行过程进行分析前,先看下测试demo: /** * @author chenyk * @date 2018年8月20日 */ public class GoodsDaoTest { pr ...

  3. Mybatis源码分析之Mapper的创建和获取

    Mybatis我们一般都是和Spring一起使用的,它们是怎么融合到一起的,又各自发挥了什么作用? 就拿这个Mapper来说,我们定义了一个接口,声明了一个方法,然后对应的xml写了这个sql语句, ...

  4. LinqToDB 源码分析——生成与执行SQL语句

    生成SQL语句的功能可以算是LinqToDB框架的最后一步.从上一章中我们可以知道处理完表达式树之后,相关生成SQL信息会被保存在一个叫SelectQuery类的实例.有了这个实例我们就可以生成对应的 ...

  5. Mybatis源码分析之Mapper文件解析

    感觉CSDN对markdown的支持不够友好,总是伴随各种问题,很恼火! xxMapper.xml的解析主要由XMLMapperBuilder类完成,parse方法来完成解析: public void ...

  6. 精尽MyBatis源码分析 - 文章导读

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  7. MyBatis源码分析-SQL语句执行的完整流程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  8. 精尽MyBatis源码分析 - SQL执行过程(二)之 StatementHandler

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

  9. 精尽MyBatis源码分析 - MyBatis 的 SQL 执行过程(一)之 Executor

    该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...

随机推荐

  1. kernel logo到开机动画之间闪现黑屏(android 5.X)

    在BootAnimation開始画图之前,会先做一次clear screen的动作,避免出现前面的图干扰到BootAnimation的显示. 通过check main_log先确认播放开机动画是哪个f ...

  2. delphi project of object

    http://www.cnblogs.com/ywangzi/archive/2012/08/28/2659811.html 其实要了解这些东西,适当的学些反汇编,WINDOWS内存管理机制,PE结构 ...

  3. 自定义一个可以被序列化的泛型Dictionary<TKey,TValue>集合

    Dictionary是一个键值类型的集合.它有点像数组,但Dictionary的键可以是任何类型,内部使用Hash Table存储键和值.本篇自定义一个类型安全的泛型Dictionary<TKe ...

  4. 项目从.NET 4.5迁移到.NET 4.0遇到的问题

    当把项目从.NET 4.5迁移到.NET 4.0时,遇到的问题和解决如下: 在"属性--应用程序--目标框架"设置成.NET 4.0版本. 重新生成项目,报有关EF的错: 卸载掉项 ...

  5. 解决SQL Server 2008提示评估期已过

    第一步:进入SQL2008配置工具中的安装中心第二步:再进入维护界面,选择版本升级第三步:进入产品密钥,输入密钥第四步:一直点下一步,直到升级完毕.SQL Server 2008 Developer: ...

  6. Android App组件之Activity

    Android App组件之Activity 1 activit介绍 Activities 是Android的四大组件之一,其余三大组件是service.broadcast和content provi ...

  7. android多设备界面适配的利器:属性weight的妙用

    1.按比例显示控件元素 <EditText android:id="@+id/edit_message" android:layout_weight="2" ...

  8. C#编程(二十七)----------创建泛型类

    创建泛型类 首先介绍一个一般的,非泛型的简化链表类,可以包含任意类型的对象,以后再把这个类转化为泛型类. 在立案表中,一个元素引用下一个元素.所以必须创建一个类,他将对象封装在链表中,并引用下一个对象 ...

  9. java集合类——Stack栈类与Queue队列

    Stack继承Vector类,它通过五个操作对类 Vector 进行了扩展. 栈是 后进先出的. 栈提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法.测试堆栈是否为空的 em ...

  10. 用UICollectionView实现无限轮播图

    用UICollectionView实现无限轮播图 效果 源码 https://github.com/YouXianMing/Animations 细节