Mybatis源码分析--Executor源码分析(未完待续)

1 概述

 Mybatis中所有的Mapper语句的执行都是通过Executor进行的,Executor是Mybatis的一个核心接口。针对Executor的学习,我们先来说说Executor的生成和Executor的分类,然后再来看看其中某个典型方法的具体执行。

2 Executor生成

Executor是通过Configuration的newExecutor函数来生成的,我们来看一看newExecutor的逻辑。

 public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
	 
    //获取执行器类型,如果没有就使用SIMPLE 
    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;
}

从上面的源码我们可以看出这里针对不同的执行器类型来生成不同的执行器,针对插件处理执行器,这里使用到了责任链模式,后面在分析插件的时候在具体谈。

2 Executor 结构

从上面的Executor的创建我们猜到了Executor仅仅是Mybatis的执行器接口,这里针对不同的执行器类型会创建不同的执行器对象。我们来看一看执行器类型枚举类。

public enum ExecutorType {
    SIMPLE, REUSE, BATCH
}

由上面的执行器类型枚举类,我们直到了Mybatis共有三种执行器。分别的作用如下:

SimpleExecutor -- 执行mapper语句的时候,默认的Executor。
ReuseExecutor -- 针对相同的sql可以重用Statement。
BatchExecutor --用于批量操作。

我们来看一下执行器的类图:

Mybatis源码分析--Executor源码分析(未完待续)