MyBatis原理分析之查询单个对象

流程原理分析系列:
MyBatis原理分析之获取SqlSessionFactory
MyBatis原理分析之获取SqlSession
MyBatis原理分析之获取Mapper接口的代理对象
MyBatis原理分析之查询单个对象

背景

  • 开启了二级缓存
  • 查询单个对象

实例代码如下:


SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
// 默认是DefaultSqlSession
SqlSession openSession = sqlSessionFactory.openSession();
try {
	// 得到的是一个代理对象 MapperProxy
	EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
	Employee employee = mapper.getEmpById(1);
	System.out.println(mapper);
	System.out.println(employee);
} finally {
	openSession.close();
}

前面我们获取的Mapper接口的代理对象,下面我们分析代理对象查询单个对象的流程。时序图如下:

在这里插入图片描述

【1】MapperProxy和MapperMethod

前面我们分析了获取Mapper接口的代理对象,会首先创建MapperProxy。MapperProxy是一个实现了InvocationHandler接口的调用处理程序,当调用Mapper接口的代理对象时,会触发MapperProxy的invoke方法。

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);
   }
 }
 //找到缓存的MapperMethod ,如果没有就新实例化一个,这个很重要
 final MapperMethod mapperMethod = cachedMapperMethod(method);
 // args是什么呢,就是触发mapper接口方法时我们传的参数,
 //其是一个Object数组,里面存放了我们传入的具体值
 return mapperMethod.execute(sqlSession, args);
}

① MapperMethod

MapperMethod是什么?先看其属性和构造函数。

public class MapperMethod {

  private final SqlCommand command;
  private final MethodSignature method;

  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    this.method = new MethodSignature(config, mapperInterface, method);
  }
//...
}

1.1 SqlCommand是什么?

其是MapperMethod的静态嵌套类,我们看其属性和构造函数。

 public static class SqlCommand {

    private final String name;
    private final SqlCommandType type;

    public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      String statementName = mapperInterface.getName() + "." + method.getName();
      MappedStatement ms = null;
      if (configuration.hasStatement(statementName)) {
        ms = configuration.getMappedStatement(statementName);
      } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35
        String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
        if (configuration.hasStatement(parentStatementName)) {
          ms = configuration.getMappedStatement(parentStatementName);
        }
      }
      if (ms == null) {
        if(method.getAnnotation(Flush.class) != null){
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): " + statementName);
        }
      } else {
        name = ms.getId();
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }

可以看到:

  • name是MappedStatement 的id,也就是namespace+mapper接口的方法名称
  • type 为UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH其中之一

也就是SqlCommand 是从MappedStatement 抽离出来的的简单标明某个MappedStatement 是一个什么样的SQL动作。

1.2 MethodSignature是什么?

方法签名,顾名思义维护了方法的诸多特征如返回类型。其是MapperMethod的静态嵌套类,MethodSignature属性和构造函数如下所示:

public static class MethodSignature {
	private final boolean returnsMany;//是否多值查询
	private final boolean returnsMap;//是否map查询
	private final boolean returnsVoid;//是否void查询
	private final boolean returnsCursor;//是否游标查询
	private final Class<?> returnType; //返回类型
	private final String mapKey;//获取mapKey的值
	//ResultHandler 参数在参数列表中的位置
	private final Integer resultHandlerIndex;
	//RowBounds 参数在参数列表中的位置
	private final Integer rowBoundsIndex;
	//参数解析器
	private final ParamNameResolver paramNameResolver; 

    public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
      Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
      if (resolvedReturnType instanceof Class<?>) {
        this.returnType = (Class<?>) resolvedReturnType;
      } else if (resolvedReturnType instanceof ParameterizedType) {
        this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
      } else {
        this.returnType = method.getReturnType();
      }
       // 检测返回值类型是否是 void、集合或数组、Cursor、Map 等
      this.returnsVoid = void.class.equals(this.returnType);
      this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray());
      this.returnsCursor = Cursor.class.equals(this.returnType);
      // 解析 @MapKey 注解,获取注解内容
      this.mapKey = getMapKey(method);
      this.returnsMap = (this.mapKey != null);
      // 获取 RowBounds 参数在参数列表中的位置,
      //如果参数列表中包含多个 RowBounds 参数,此方法会抛出异常
      this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
      // 获取 ResultHandler 参数在参数列表中的位置
      this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
      //获取参数解析器,构造函数会解析方法的参数列表
      this.paramNameResolver = new ParamNameResolver(configuration, method);
    }
 //...
}   

代码解释如下:

  • ① 获取返回类型
  • ② 判断返回类型是否是 void、集合或数组、Cursor、Map 等
  • ③ 获取mapKey并判断是否返回Map,不存在则为null;
  • ④ 确定RowBounds在参数列表的位置,如果有多个则抛出异常;不存在则为null。
  • ⑤ 确定ResultHandler在参数列表的位置,如果有多个则抛出异常;不存在则为null。
  • ⑥ 实例化参数解析器ParamNameResolver

1.3 ParamNameResolver是什么?

顾名思义,参数名称解析器。在实例化方法签名MethodSignature会实例化ParamNameResolver。我们看下属性和构造函数,构造方法最重要的功能就是实例化了SortedMap<Integer, String> names,该SortedMap维护了方法的参数下标与参数名称的映射关系。

public class ParamNameResolver {

  private static final String GENERIC_NAME_PREFIX = "param";
  private static final String PARAMETER_CLASS = "java.lang.reflect.Parameter";
  private static Method GET_NAME = null;
  private static Method GET_PARAMS = null;

  static {
    try {
      Class<?> paramClass = Resources.classForName(PARAMETER_CLASS);
      GET_NAME = paramClass.getMethod("getName");
      GET_PARAMS = Method.class.getMethod("getParameters");
    } catch (Exception e) {
      // ignore
    }
  }
  //维护了方法的参数 索引下标--参数名称 
  private final SortedMap<Integer, String> names;
  private boolean hasParamAnnotation;
  public ParamNameResolver(Configuration config, Method method) {
    final Class<?>[] paramTypes = method.getParameterTypes();
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
    int paramCount = paramAnnotations.length;
    // get names from @Param annotations
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      if (isSpecialParameter(paramTypes[paramIndex])) {
        // skip special parameters
        continue;
      }
      String name = null;
      for (Annotation annotation : paramAnnotations[paramIndex]) {
        if (annotation instanceof Param) {
          hasParamAnnotation = true;
          name = ((Param) annotation).value();
          break;
        }
      }
      if (name == null) {
        // @Param was not specified. useActualParamName 属性在新版本mybatis中默认为TRUE!
        if (config.isUseActualParamName()) {
          name = getActualParamName(method, paramIndex);
        }
        if (name == null) {
          // use the parameter index as the name ("0", "1", ...)
          // gcode issue #71
          name = String.valueOf(map.size());
        }
      }
      map.put(paramIndex, name);
    }
    names = Collections.unmodifiableSortedMap(map);
  }
//...
}  

这里先看下常量成员SortedMap<Integer, String> names

//其实一个UnmodifiableSortedMap类型,排序且不可修改
private final SortedMap<Integer, String> names

其javadoc说明如下:

  • key是索引index,值是参数的名称;
  • 如果参数被@Param注解重命名,则取其注解值作为name值;
  • 如果么有使用@Params注解,则取其参数索引作为name值;
    • 注意,参数索引不计算RowBounds、ResultHandler类型
    aMethod(@Param("M") int a, @Param("N") int b) -> {{0, "M"}, {1, "N"}};
    aMethod(int a, int b) -> {{0, "0"}, {1, "1"}};
    //跳过RowBounds rb
    aMethod(int a, RowBounds rb, int b) -> {{0, "0"}, {2, "1"}}
    

也就是说names里面保存的是第几个参数对应的参数名称是什么。

然后我们解释下构造函数的内容

  • 判断当前参数类型是否RowBound或ResultHandler,如果是则进行下次循环;
  • 如果有@Param注解,则@Param注解的值作为name的值;
  • 如果configuration中useActualParamName为true,则根据参数索引解析参数name值,诸如arg0、arg1…
  • 获取当前map的大小作为name的值

SortedMap<Integer, String> names可能如下:

//@Param("idxxx")  id
{0=idxx}
//configuration中useActualParamName为true
{0=arg0}
//前两种都不存在
{0=0}

如下图是一个names实例:
在这里插入图片描述

Object execute(SqlSession sqlSession, Object[] args)

MapperMethodexecute方法是核心入口方法,调用MapperProxy的invoke方法中就会触发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;
  }

代码解释如下:

  • ① 根据command.getType也就SQL动作类型,判断走哪个分支;
  • method.convertArgsToSqlCommandParam(args)解析参数,可能返回一个单独值或者map
  • ③ 根据②返回的参数进行不同分支的CRUD,拿到结果result;
  • ④ 判断是否抛出异常或者返回result。

③ 参数解析convertArgsToSqlCommandParam

这里我们看一下method.convertArgsToSqlCommandParam(args)是如何解析参数的。该方法内部调用了paramNameResolver.getNamedParams(args)

这里names{"0":"0"},args[1] ,args是传递的参数值,是一个Object[]

//也就是获取Object[] args中每一个值对应的参数key是什么
public Object getNamedParams(Object[] args) {
	final int paramCount = names.size();
	if (args == null || paramCount == 0) {
	  return null;
	} else if (!hasParamAnnotation && paramCount == 1) {
	  return args[names.firstKey()];
	} else {
	  final Map<String, Object> param = new ParamMap<Object>();
	  int i = 0;
	  for (Map.Entry<Integer, String> entry : names.entrySet()) {
	    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++;
	  }
	  return param;
}

代码解释如下:

  • ① 如果argsnull或者names为空,直接返回null
  • ② 如果没有使用@Param注解并且names.size()==1,直接返回args[names.firstKey()]
  • ③ 遍历names.entrySet,向里面放入两种类型键值对:
     param.put(entry.getValue(), args[entry.getKey()]);
     param.put(genericParamName, args[entry.getKey()]);
     这里如{"0":"1","param1":"1"}
    

【2】DefaultSqlSession

回顾一下DefaultSqlSession的核心成员与构造方法如下,其核心成员 configuration 与 exceutor均是private final修饰也就是赋值后不可再更改。在实例化DefaultSqlSession时,已经为其指定了执行器Executor ,这是进行DML操作的基础组件。

private final Configuration configuration;
private final Executor executor;

private final boolean autoCommit;
private boolean dirty;
private List<Cursor<?>> cursorList;

public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
  this.configuration = configuration;
  this.executor = executor;
  this.dirty = false;
  this.autoCommit = autoCommit;
}

① selectOne

方法源码如下:

@Override
public <T> T selectOne(String statement, Object parameter) {
  // Popular vote was to return null on 0 results and throw exception on too many.
  List<T> list = this.<T>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;
  }
}

这里statement就是ms的id,就是namespace+方法名称(insert|update|select|delete的id),如com.mybatis.dao.EmployeeMapper.getEmpById
parameter就是前面解析的参数值或者参数-值Map集合。

代码解释如下:

  • ① 调用selectList获取结果list;
  • ② 如果①中获取的结果list只有一个值,直接返回;
  • ③ 如果①中获取的结果list.size()>1,抛出异常;
  • ④ 否则返回null。

② selectList

相关代码如下:

@Override
public <E> List<E> selectList(String statement, Object parameter) {
  return this.selectList(statement, parameter, RowBounds.DEFAULT);
}

@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    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();
  }
}

代码解释如下:

  • 根据statementconfig实例的final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>中获取MappedStatement 对象
  • 对参数值(parameter对象)进行集合包装后,使用executor进行查询

wrapCollection方法如下所示:

  private Object wrapCollection(final Object object) {
    if (object instanceof Collection) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("collection", object);
      if (object instanceof List) {
        map.put("list", object);
      }
      return map;
    } else if (object != null && object.getClass().isArray()) {
      StrictMap<Object> map = new StrictMap<Object>();
      map.put("array", object);
      return map;
    }
    return object;
  }

代码解释如下:

  • ① 如果是Collection类型
    • ② 不是List类型,则往StrictMap中放入 map.put("collection", object);,返回map
    • ③ 是List类型,则在②基础上额外放入map.put("list", object);然后返回map
  • ④ 如果是Array类型,则放入map.put("array", object);,返回map
  • ⑤ 返回object

【3】CachingExecutor

CachingExecutor属性和构造函数如下:

public class CachingExecutor implements Executor {

  private Executor delegate;
  private TransactionalCacheManager tcm = new TransactionalCacheManager();

  public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    delegate.setExecutorWrapper(this);
  }
//...
}  

TransactionalCacheManager属性如下(无有参构造方法)

public class TransactionalCacheManager {

  private Map<Cache, TransactionalCache> transactionalCaches = new HashMap<Cache, TransactionalCache>();
  //...
}  

TransactionalCache属性和构造函数如下:

public class TransactionalCache implements Cache {
  private static final Log log = LogFactory.getLog(TransactionalCache.class);
  //实际缓存对象
  private Cache delegate;
  private boolean clearOnCommit;
  //缓存key---查询结果
  private Map<Object, Object> entriesToAddOnCommit;
  //没有对应value的缓存key
  private Set<Object> entriesMissedInCache;

  public TransactionalCache(Cache delegate) {
    this.delegate = delegate;
    this.clearOnCommit = false;
    this.entriesToAddOnCommit = new HashMap<Object, Object>();
    this.entriesMissedInCache = new HashSet<Object>();
  }
//...
}  

通过上面代码可以看到:

  • 每一个CachingExecutor 有一个对应的TransactionalCacheManager(事务缓存管理器)。
  • 每一个TransactionalCacheManager维护了一个Map<Cache, TransactionalCache> transactionalCaches

回顾一下,每一个SqlSession有一个成员Executormapper接口的代理对象是通过SqlSession获取的,代理对象有指向sqlsession实例的引用。所以在一次会话间,如果对不同namespace进行了CRUD操作,那么所遇到的Cache可能有多个。故而这里transactionalCaches 是一个new HashMap<Cache, TransactionalCache>();类型,也标明了二级缓存的级别是namespace

言归正传,我们继续看查询过程。

@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
  BoundSql boundSql = ms.getBoundSql(parameterObject);
  CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
  return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}

① 获取BoundSql

MappedStatement.getBoundSql方法源码如下:

  public BoundSql getBoundSql(Object parameterObject) {
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings == null || parameterMappings.isEmpty()) {
      boundSql = new BoundSql(configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject);
    }

    // check for nested result maps in parameter mappings (issue #30)
    for (ParameterMapping pm : boundSql.getParameterMappings()) {
      String rmId = pm.getResultMapId();
      if (rmId != null) {
        ResultMap rm = configuration.getResultMap(rmId);
        if (rm != null) {
          hasNestedResultMaps |= rm.hasNestedResultMaps();
        }
      }
    }
    return boundSql;
  }

代码解释如下:

  • ① 根据sqlSource和参数值对象parameterObject获取BoundSql。每一个MappedStatement都有一个SqlSource实例,sqlsource实例如下:
    在这里插入图片描述
  • ② 如果①中获取的boundSql对象的parameterMappings为空,则新建一个BoundSql实例对象;
  • ③ 对boundSql对象的parameterMappings进行遍历循环,判断在ParameterMapping中是否有嵌套结果映射。
    在这里插入图片描述

② 获取CacheKey

装饰者模式的应用,CachingExecutor内部有一个被装饰者Executor delegate

@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
  return delegate.createCacheKey(ms, parameterObject, rowBounds, boundSql);
}

可以看到这里CachingExecutor交给了其装饰的delegate(这里是SimpleExecutor)来处理。SimpleExecutor将会调用父类BaseExecutorcreateCacheKey方法进行处理

@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
 if (closed) {
   throw new ExecutorException("Executor was closed.");
 }
 CacheKey cacheKey = new CacheKey();
 cacheKey.update(ms.getId());
 cacheKey.update(rowBounds.getOffset());
 cacheKey.update(rowBounds.getLimit());
 cacheKey.update(boundSql.getSql());
 List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
 TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
 // mimic DefaultParameterHandler logic
 for (ParameterMapping parameterMapping : parameterMappings) {
   if (parameterMapping.getMode() != ParameterMode.OUT) {
     Object value;
     String propertyName = parameterMapping.getProperty();
     if (boundSql.hasAdditionalParameter(propertyName)) {
       value = boundSql.getAdditionalParameter(propertyName);
     } else if (parameterObject == null) {
       value = null;
     } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
       value = parameterObject;
     } else {
       MetaObject metaObject = configuration.newMetaObject(parameterObject);
       value = metaObject.getValue(propertyName);
     }
     cacheKey.update(value);
   }
 }
 if (configuration.getEnvironment() != null) {
   // issue #176
   cacheKey.update(configuration.getEnvironment().getId());
 }
 return cacheKey;
}

CacheKey是什么?

每个MappedStatement都可能对应一个CacheKey,唯一标识在Cache中的存储。

public class CacheKey implements Cloneable, Serializable {

  private static final long serialVersionUID = 1146682552656046210L;

  public static final CacheKey NULL_CACHE_KEY = new NullCacheKey();

  private static final int DEFAULT_MULTIPLYER = 37;
  private static final int DEFAULT_HASHCODE = 17;

  private int multiplier;
  private int hashcode;
  private long checksum;
  private int count;
  private List<Object> updateList;

  public CacheKey() {
    this.hashcode = DEFAULT_HASHCODE;
    this.multiplier = DEFAULT_MULTIPLYER;
    this.count = 0;
    this.updateList = new ArrayList<Object>();
  }
//...
}  
private void doUpdate(Object object) {
	int baseHashCode = object == null ? 1 : object.hashCode();
	//默认值 0
	count++;
	checksum += baseHashCode;
	baseHashCode *= count;
	//默认值37 hashcode默认值17
	hashcode = multiplier * hashcode + baseHashCode;
	
	updateList.add(object);
}

算法逻辑解释如下:

  • ① 计算每个入参的hashCode作为baseHashCode
  • ② 计算次数或者处理次数count +1;
  • checksum 记录目前为止所有入参的hashCode和;
  • hashcode = multiplier * hashcode + baseHashCode*count;
  • ⑤将当前object放入updateList

这里得到的CacheKey如下所示:

-272712784:4091614186:com.mybatis.dao.EmployeeMapper.getEmpById:0:2147483647
:select id,last_name lastName,email,gender from tbl_employee where id = ?
:1:development

hashcode:checksum:ms.getId():rowBounds.getOffset():rowBounds.getLimit():boundSql.getSql():value:environment.getId()


③ query查询数据

CachingExecutorquery方法如下:

//参数parameterObject指的是参数值对象
@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);
}

代码解释如下:

  • ① 获取当前MappedStatementd对应的二级缓存对象Cache;
  • ② 如果Cache不为空:
    • ③ 判断是否需要清空缓存,需要则清空;
    • ④ 如果isUseCachetrueresultHandler为空则执行5678,否则直接执行9
      • ⑤ 确保没有out类型参数-针对StatementType.CALLABLE而言,只适用于ParameterMode.IN
      • ⑥ 从缓存中获取结果list
        • ⑦ 如果结果list不为空则直接返回;
        • ⑧ 如果list为空则进行数据库查询然后将查询结果放入缓存Cache中;
  • ⑨ 如果Cache为空,则直接调用数据库查询结果

【4】BaseExecutor

CachingExecutor将数据库查询操作交给了SimpleExecutor(CachingExecutorSimpleExecutor进行了装饰)。而SimpleExecutor继承自抽象父类BaseExecutor,并没有覆盖父类的 query方法,故而这里直接走到BaseExecutorquery方法。

① query

 @SuppressWarnings("unchecked")
  @Override
  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;
  }

代码解释如下:

  • ① 如果需要,则清理本地缓存localCachelocalOutputParameterCache-这是CALLABLE类型中参数为out类型;
  • ② 如果resultHandlernull,则尝试从本地缓存中根据缓存key获取结果list:
    • ③ 如果list不为null,则尝试处理CALLABLE类型中参数为out类型(如果当前是CALLABLE且参数为out`类型);
    • ④ 如果listnull,则进行数据库查询;
  • ⑤ 如果deferredLoads不为空,则遍历循环进行延迟加载处理。处理完后,清空deferredLoads
  • ⑥ 如果localCacheScope==STATEMENT,则清空一级缓存;

② queryFromDatabase

查询方法如下所示,这里参数中key是缓存key,parameter是参数值对象(可能是一个值,也可能是一个map等)。

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

代码解释如下:

  • localCache本地一级缓存中放入当前缓存key与占位对象;
  • ② 执行数据库查询;
  • ③ 从localCache移除key,然后放入key-list
  • ④ 如果当前语句是CALLABLE,则将key-parameter放入localOutputParameterCache

这里需要注意的是,localCache默认是PerpetualCache实例,其内部使用private Map<Object, Object> cache = new HashMap<>();维护缓存数据。而PerpetualCache实例是BaseExecutor实例的一个普通成员,并没有使用ThreadLocal维护。所以如果多个线程使用同一个sqlsession实例进行数据库操作的时候 ,可能出现并发问题,sqlsession并非线程安全!

如下图所示,在 localCache.putObject(key, list);处中断,线程1读取数据库结果为2条,线程2读取了3条,那么此时无论谁先更新缓存,对其都可能造成“幻读”错觉!如何解决sqlsession线程不安全问题呢?最好的方案是保证每一个事务或线程拥有独属的sqlsession!
在这里插入图片描述

【5】SimpleExecutor

① doQuery

前面的query可以理解为前置处理、后置处理,这里doQuery是解析参数、查询数据并处理返回结果的核心方法。

@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);
    stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}

代码解释如下:

  • ① 获取全局的configuration实例;
  • ② 获取RoutingStatementHandler实例,在此过程中还会创建ParameterHandler和ResultSetHandler实例。interceptorChain.pluginAll对StatementHandler实例进行代理。
  • ③ 获取预编译处理语句并进行参数解析;
  • ④ 使用StatementHandler 进行查询;
  • closeStatement关闭连接等,然后返回结果。

MyBatis提供了一种插件机制,具体来说就是四大对象Executor、StatementHandler、ParameterHandler、ResultSetHandler的每个对象在创建时,都会执行interceptorChain.pluginAll(),会经过每个插件对象的 plugin()方法,目的是为当前的四大对象创建代理。代理对象就可以拦截到四大对象相关方法的执行,因为要执行四大对象的方法需要经过代理 。

接下来我们详细分析②③④的具体过程。

② configuration.newStatementHandler

 public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
    return statementHandler;
  }

代码解释如下:

  • ① 先创建RoutingStatementHandler实例;
  • ② 对statementHandler 实例进行拦截器层层代理;

RoutingStatementHandler

RoutingStatementHandler属性和构造函数。

public class RoutingStatementHandler implements StatementHandler {

private final StatementHandler delegate;

public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

  switch (ms.getStatementType()) {
    case STATEMENT:
      delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
      break;
    case PREPARED:
      delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
      break;
    case CALLABLE:
      delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
      break;
    default:
      throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
  }
}
//...
}

可以看到RoutingStatementHandler 内部维护了一个StatementHandler delegate成员,RoutingStatementHandlerdelegate进行了装饰/包装,具体工作交给delegate处理。根据StatementType类型不同创建不同的delegate 实例。这里创建的是PreparedStatementHandler实例。

BaseStatementHandler

PreparedStatementHandler直接调用了抽象父类BaseStatementHandler 的构造函数。

public abstract class BaseStatementHandler implements StatementHandler {
  //全局配置实例
  protected final Configuration configuration;
  //对象工厂
  protected final ObjectFactory objectFactory;
  //类型转换处理器
  protected final TypeHandlerRegistry typeHandlerRegistry;
  //结果处理器
  protected final ResultSetHandler resultSetHandler;
  //参数处理器
  protected final ParameterHandler parameterHandler;
  //执行器
  protected final Executor executor;
  //映射语句对象
  protected final MappedStatement mappedStatement;
  //分页对象
  protected final RowBounds rowBounds;
 //SQL信息
  protected BoundSql boundSql;

  protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
    this.configuration = mappedStatement.getConfiguration();
    this.executor = executor;
    this.mappedStatement = mappedStatement;
    this.rowBounds = rowBounds;

    this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
    this.objectFactory = configuration.getObjectFactory();

    if (boundSql == null) { // issue #435, get the key before calculating the statement
      generateKeys(parameterObject);
      boundSql = mappedStatement.getBoundSql(parameterObject);
    }

    this.boundSql = boundSql;
	//非常重要-参数处理器
    this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
    //非常重要 -多结果集处理器
    this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
  }

上面可以看到,在构造函数中先创建了parameterHandler 实例,然后根据parameterHandler 实例创建了resultSetHandler 实例。

newParameterHandler

public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
  ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
  parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
  return parameterHandler;
}

代码解释如下:

  • ① 创建ParameterHandler,默认是DefaultParameterHandler实例;
  • interceptorChain.pluginAll进行层层插件代理,返回一个代理对象。
    在这里插入图片描述

XMLLanguageDriver创建createParameterHandler代码如下:

@Override
  public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
    return new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
  }

InterceptorChain.pluginAll

InterceptorChain内部维护了一个List<Interceptor> interceptors,pluginAll方法就是对目标对象层层代理。

 public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }

我们可以看下mybatis中的Interceptor 在这里插入代码片

package org.apache.ibatis.plugin;
import java.util.Properties;
public interface Interceptor {
  Object intercept(Invocation invocation) throws Throwable;
  Object plugin(Object target);
  void setProperties(Properties properties);
}

其提供了了plugin方法用来生成代理对象,intercept方法用来在执行目标方法前进行拦截处理。

如下所示,是mybatisplus中分页插件实现的plugin方法。其调用了Plugin.wrap(target, this)来为StatementHandler实例对象生成代理对象。

@Override
  public Object plugin(Object target) {
      if (target instanceof StatementHandler) {
          return Plugin.wrap(target, this);
      }
      return target;
  }

mybatis中的org.apache.ibatis.plugin.Plugin主要属性和方法如下所示:

public class Plugin implements InvocationHandler {

  private final Object target;
  private final Interceptor interceptor;
  private final Map<Class<?>, Set<Method>> signatureMap;

  private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
    this.target = target;
    this.interceptor = interceptor;
    this.signatureMap = signatureMap;
  }

  public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }
//...
}

可以看到Plugin实现了InvocationHandler接口。其wrap方法为target生成了代理对象,当执行目标方法时,会首先触发Plugininvoke方法。在invoke方法里面调用了interceptorintercept方法。


newResultSetHandler

  public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
      ResultHandler resultHandler, BoundSql boundSql) {
    ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
    resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
    return resultSetHandler;
  }

代码解释如下:

  • ① 创建DefaultResultSetHandler实例;
  • interceptorChain.pluginAll对resultSetHandler 进行层层代理包装,返回代理对象。

顺便看一下我们最后得到的StatementHandler
在这里插入图片描述


③ SimpleExecutor.prepareStatement

SimpleExecutor.prepareStatement(StatementHandler, Log) 方法源码如下,这里handler就是前面创建的RoutingStatementHandler .

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }

代码解释如下:

  • stmt = handler.prepare(connection, transaction.getTimeout());意识是使用StatementHandler 进行预处理获取Statement 对象。
  • handler.parameterize(stmt)使用handler对①获取的Statement 对象进行参数解析。

RoutingStatementHandler交给了其装饰的对象PreparedStatementHandle处理,PreparedStatementHandle调用了其抽象父类BaseStatementHandler处理。

 @Override
  public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
    return delegate.prepare(connection, transactionTimeout);
  }

BaseStatementHandlerprepare方法

@Override
public Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException {
  ErrorContext.instance().sql(boundSql.getSql());
  Statement statement = null;
  try {
    statement = instantiateStatement(connection);
    setStatementTimeout(statement, transactionTimeout);
    setFetchSize(statement);
    return statement;
  } catch (SQLException e) {
    closeStatement(statement);
    throw e;
  } catch (Exception e) {
    closeStatement(statement);
    throw new ExecutorException("Error preparing statement.  Cause: " + e, e);
  }
}

代码解释如下:

  • ① 实例化Statement对象;
  • ② 设置超时时间;
  • ③ 设置每次批量返回的结果行数

PreparedStatementHandlerinstantiateStatement方法

@Override
protected Statement instantiateStatement(Connection connection) throws SQLException {
  String sql = boundSql.getSql();
  if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
    String[] keyColumnNames = mappedStatement.getKeyColumns();
    if (keyColumnNames == null) {
      return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
    } else {
      return connection.prepareStatement(sql, keyColumnNames);
    }
  } else if (mappedStatement.getResultSetType() != null) {
    return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
  } else {
    return connection.prepareStatement(sql);
  }
}

代码解释如下:

  • ① 获取处理前的SQL,这时候带有占位符?
    select id,last_name lastName,email,gender from tbl_employee where id = ?
    
  • ② 如果KeyGeneratorJdbc3KeyGenerator类型,则根据keyColumnNames 是否为null进行不同处理;
  • ③ 如果ResultSetType不为null,则根据ResultSetType获取Statement对象;
  • ④ 否则只根据SQL获取Statement对象。

如下图所示,这里获取的Statement对象也是一个代理对象,实际对象是com.mysql.jdbc.JDBC42PreparedStatement@4dbb42b7: select id,last_name lastName,email,gender from tbl_employee where id = ** NOT SPECIFIED **
在这里插入图片描述

handler.parameterize(stmt)

如下所示,这里RoutingStatementHandler交给了其装饰对象PreparedStatementHandler去处理。

RoutingStatementHandler的parameterize方法如下:

@Override
public void parameterize(Statement statement) throws SQLException {
 delegate.parameterize(statement);
}

PreparedStatementHandler的parameterize方法如下

@Override
public void parameterize(Statement statement) throws SQLException {
  parameterHandler.setParameters((PreparedStatement) statement);
}

这里parameterHandler如下所示:
在这里插入图片描述

DefaultParameterHandler的setParameters方法

@Override
public void setParameters(PreparedStatement ps) {
  ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  if (parameterMappings != null) {
    for (int i = 0; i < parameterMappings.size(); i++) {
      ParameterMapping parameterMapping = parameterMappings.get(i);
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        Object value;
        String propertyName = parameterMapping.getProperty();
        if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
          value = boundSql.getAdditionalParameter(propertyName);
        } else if (parameterObject == null) {
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          value = parameterObject;
        } else {
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        TypeHandler typeHandler = parameterMapping.getTypeHandler();
        JdbcType jdbcType = parameterMapping.getJdbcType();
        if (value == null && jdbcType == null) {
          jdbcType = configuration.getJdbcTypeForNull();
        }
        try {
          typeHandler.setParameter(ps, i + 1, value, jdbcType);
        } catch (TypeException e) {
          throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
        } catch (SQLException e) {
          throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
        }
      }
    }
  }
}

代码解释如下:

  • ① 根据boundSql获取parameterMappings进行遍历处理;
  • ② 如果parameterMapping.getMode() == ParameterMode.OUT,直接跳过进行下次循环;
  • ③ 获取propertyName和value;
  • typeHandler.setParameter(ps, i + 1, value, jdbcType)对本地循环的参数进行赋值

我们对第④步详细跟踪一下。默认情况下,如果不设置TypeHandler,那么这里获取到的TypeHandler实例为UnknownTypeHandler,其继承于BaseTypeHandler。这里会走到UnknownTypeHandlersetNonNullParameter方法。

@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
 throws SQLException {
TypeHandler handler = resolveTypeHandler(parameter, jdbcType);
handler.setParameter(ps, i, parameter, jdbcType);
}

可以看到,其首先根据参数与jdbcType解析handler ,然后使用handlerps中参数占位符赋值。

其解析TypeHandler主要逻辑如下所示:

private TypeHandler<? extends Object> resolveTypeHandler(Object parameter, JdbcType jdbcType) {
  TypeHandler<? extends Object> handler;
  if (parameter == null) {
    handler = OBJECT_TYPE_HANDLER;
  } else {
    handler = typeHandlerRegistry.getTypeHandler(parameter.getClass(), jdbcType);
    // check if handler is null (issue #270)
    if (handler == null || handler instanceof UnknownTypeHandler) {
      handler = OBJECT_TYPE_HANDLER;
    }
  }
  return handler;
}

代码解释如下:

  • ① 如果parameternull,则handlerObjectTypeHandler;
  • ② 否则根据参数类型、jdbcTypetypeHandlerRegistryTYPE_HANDLER_MAP集合中获取;

处理完后的statement实例如下所示,SQL中参数占位符已经被赋予实际值,$Proxy6表示其是一个代理对象。
在这里插入图片描述

handler.<E>query(stmt, resultHandler)

RoutingStatementHandler交给装饰对象PreparedStatementHandler进行查询。

@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
  return delegate.<E>query(statement, resultHandler);
}

PreparedStatementHandlerquery方法如下。

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

代码解释如下:

  • ① 转换为PreparedStatement 类型然后调用其execute方法,由于其是代理对象,故而会先触发其调用处理程序PreparedStatementLoggerinvoke方法。
  • ② 使用DefaultResultSetHandler处理结果集

PreparedStatementLogger.invoke方法

EXECUTE_METHODS值如下:

[addBatch, execute, executeUpdate, executeQuery]

SET_METHODS值如下:

[setBytes, setFloat, setBigDecimal, setByte, setNull, setShort, setObject, setInt, setArray, setNCharacterStream,
setDouble, setNClob, setString, setLong, setCharacterStream, setAsciiStream, setClob, setBlob, setDate, 
setBinaryStream, setNString, setTimestamp, setTime, setBoolean]
@Override
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
  try {
    if (Object.class.equals(method.getDeclaringClass())) {
      return method.invoke(this, params);
    }          
    //[addBatch, execute, executeUpdate, executeQuery]
    if (EXECUTE_METHODS.contains(method.getName())) {
      if (isDebugEnabled()) {
        debug("Parameters: " + getParameterValueString(), true);
      }
      clearColumnInfo();
      if ("executeQuery".equals(method.getName())) {
        ResultSet rs = (ResultSet) method.invoke(statement, params);
        return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);
      } else {
        return method.invoke(statement, params);
      }
    } else if (SET_METHODS.contains(method.getName())) {
      if ("setNull".equals(method.getName())) {
        setColumn(params[0], null);
      } else {
        setColumn(params[0], params[1]);
      }
      return method.invoke(statement, params);
    } else if ("getResultSet".equals(method.getName())) {
      ResultSet rs = (ResultSet) method.invoke(statement, params);
      return rs == null ? null : ResultSetLogger.newInstance(rs, statementLog, queryStack);
    } else if ("getUpdateCount".equals(method.getName())) {
      int updateCount = (Integer) method.invoke(statement, params);
      if (updateCount != -1) {
        debug("   Updates: " + updateCount, false);
      }
      return updateCount;
    } else {
      return method.invoke(statement, params);
    }
  } catch (Throwable t) {
    throw ExceptionUtil.unwrapThrowable(t);
  }
}

代码解释如下:

  • ① 判断方法所属声明类型为object,则直接反射调用方法;
  • ② 判断方法名是否在EXECUTE_METHODS内,进而判断是否为executeQuery,进行不同处理;
  • ③ 判断方法名是否在SET_METHODS内,如果是,则首先进行setColumn处理;
  • ④ 判断方法名是否为getResultSet;
  • ⑤ 判断方法名是否为getUpdateCount;
  • ⑥ 以上都没有执行,则直接进行方法反射。

如下图所示,方法为public abstract boolean java.sql.PreparedStatement.execute() throws java.sql.SQLException
在这里插入图片描述
statement对象为JDBC42PreparedStatement,那么方法最终会走到PreparedStatement.execute() 方法。在MySQL5中public class PreparedStatement extends com.mysql.jdbc.StatementImpl implements java.sql.PreparedStatement

这里可以看一下其execute方法(这里不用做深入研究,只需要知道方法执行后,就拿到了结果集resultSet):

public boolean execute() throws SQLException {
        synchronized (checkClosed().getConnectionMutex()) {
            MySQLConnection locallyScopedConn = this.connection;
            if (!checkReadOnlySafeStatement()) {
                throw SQLError.createSQLException(Messages.getString("PreparedStatement.20") + Messages.getString("PreparedStatement.21"),
                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
            }
            ResultSetInternalMethods rs = null;
            CachedResultSetMetaData cachedMetadata = null;
            this.lastQueryIsOnDupKeyUpdate = false;
            if (this.retrieveGeneratedKeys) {
                this.lastQueryIsOnDupKeyUpdate = containsOnDuplicateKeyUpdateInSQL();
            }
            clearWarnings();
            setupStreamingTimeout(locallyScopedConn);
            this.batchedGeneratedKeys = null;
            Buffer sendPacket = fillSendPacket();
            String oldCatalog = null;
            if (!locallyScopedConn.getCatalog().equals(this.currentCatalog)) {
                oldCatalog = locallyScopedConn.getCatalog();
                locallyScopedConn.setCatalog(this.currentCatalog);
            }
            //
            // Check if we have cached metadata for this query...
            //
            if (locallyScopedConn.getCacheResultSetMetadata()) {
                cachedMetadata = locallyScopedConn.getCachedMetaData(this.originalSql);
            }
            Field[] metadataFromCache = null;
            if (cachedMetadata != null) {
                metadataFromCache = cachedMetadata.fields;
            }
            boolean oldInfoMsgState = false;

            if (this.retrieveGeneratedKeys) {
                oldInfoMsgState = locallyScopedConn.isReadInfoMsgEnabled();
                locallyScopedConn.setReadInfoMsgEnabled(true);
            }
            //
            // Only apply max_rows to selects
            //
            locallyScopedConn.setSessionMaxRows(this.firstCharOfStmt == 'S' ? this.maxRows : -1);

            rs = executeInternal(this.maxRows, sendPacket, createStreamingResultSet(), (this.firstCharOfStmt == 'S'), metadataFromCache, false);

            if (cachedMetadata != null) {
                locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, cachedMetadata, rs);
            } else {
                if (rs.reallyResult() && locallyScopedConn.getCacheResultSetMetadata()) {
                    locallyScopedConn.initializeResultsMetadataFromCache(this.originalSql, null /* will be created */, rs);
                }
            }
            if (this.retrieveGeneratedKeys) {
                locallyScopedConn.setReadInfoMsgEnabled(oldInfoMsgState);
                rs.setFirstCharOfQuery(this.firstCharOfStmt);
            }
            if (oldCatalog != null) {
                locallyScopedConn.setCatalog(oldCatalog);
            }
            if (rs != null) {
                this.lastInsertId = rs.getUpdateID();

                this.results = rs;
            }
            return ((rs != null) && rs.reallyResult());
        }
    }

DefaultResultSetHandler.handleResultSets方法

 @Override
  public List<Object> handleResultSets(Statement stmt) throws SQLException {
    ErrorContext.instance().activity("handling results").object(mappedStatement.getId());

    final List<Object> multipleResults = new ArrayList<Object>();

    int resultSetCount = 0;
    // 得到第一个ResultSet,也就是before the first row  
    ResultSetWrapper rsw = getFirstResultSet(stmt);

	// 获取当前statement的实体-属性结果映射
    List<ResultMap> resultMaps = mappedStatement.getResultMaps();
    int resultMapCount = resultMaps.size();
    validateResultMapsCount(rsw, resultMapCount);
    while (rsw != null && resultMapCount > resultSetCount) {
      ResultMap resultMap = resultMaps.get(resultSetCount);
      handleResultSet(rsw, resultMap, multipleResults, null);
      rsw = getNextResultSet(stmt);
      cleanUpAfterHandlingResultSet();
      resultSetCount++;
    }

    String[] resultSets = mappedStatement.getResultSets();
    if (resultSets != null) {
      while (rsw != null && resultSetCount < resultSets.length) {
        ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
        if (parentMapping != null) {
          String nestedResultMapId = parentMapping.getNestedResultMapId();
          ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
          handleResultSet(rsw, resultMap, null, parentMapping);
        }
        rsw = getNextResultSet(stmt);
        cleanUpAfterHandlingResultSet();
        resultSetCount++;
      }
    }

    return collapseSingleResultList(multipleResults);
  }

代码解释如下:

  • ① 获取ResultSetWrapper
  • ② 获取resultMaps
  • ③ 对resultMaps进行循环处理;
  • ④ 获取resultSets 然后进行循环处理;
  • ⑥ 如果multipleResults集合只有一个元素则返回第一个元素,否则返回multipleResults

获取到的ResultSetWrapper rsw如下图所示:

此时指针并没有指向数据集的第一条,而是Before start of result set,currRowIndex=-1。rs是个代理对象。
在这里插入图片描述
获取到的 List<ResultMap> resultMaps如下图所示(xml中当前查询没有指定resultMap,这是mybatis默认创建的):
在这里插入图片描述
这里我们跟踪一下handleResultSet(rsw, resultMap, multipleResults, null);如下所示。

private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
 try {
   if (parentMapping != null) {
     handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
   } else {
     if (resultHandler == null) {
       DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
       handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
       multipleResults.add(defaultResultHandler.getResultList());
     } else {
       handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
     }
   }
 } finally {
   // issue #228 (close resultsets)
   closeResultSet(rsw.getResultSet());
 }
}

这里会创建默认的DefaultResultHandler 实例对象,然后调用核心方法handleRowValues处理行记录值。这里会把defaultResultHandler.getResultList()放到multipleResults中,multipleResults是一个List<Object>

DefaultResultHandler 只有一个List<Object> list属性,其作为当前上下文处理结果的容器,存放结果集(RowValue或者说ResultObject集合)。

public class DefaultResultHandler implements ResultHandler<Object> {
  private final List<Object> list;
  public DefaultResultHandler() {
    list = new ArrayList<Object>();
  }
  @SuppressWarnings("unchecked")
  public DefaultResultHandler(ObjectFactory objectFactory) {
    list = objectFactory.create(List.class);
  }
  @Override
  public void handleResult(ResultContext<? extends Object> context) {
    list.add(context.getResultObject());
  }
  public List<Object> getResultList() {
    return list;
  }
}

DefaultResultSetHandler.handleRowValues方法如下:

public void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  if (resultMap.hasNestedResultMaps()) {
    ensureNoRowBounds();
    checkResultHandler();
    handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  } else {
    handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  }
}

会根据是否有嵌套结果映射来走不同的处理逻辑,这里我们走的是handleRowValuesForSimpleResultMap


DefaultResultSetHandler.handleRowValuesForSimpleResultMap方法如下所示:

private void handleRowValuesForSimpleResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler<?> resultHandler, RowBounds rowBounds, ResultMapping parentMapping)
    throws SQLException {
  DefaultResultContext<Object> resultContext = new DefaultResultContext<Object>();
  skipRows(rsw.getResultSet(), rowBounds);
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    Object rowValue = getRowValue(rsw, discriminatedResultMap);
    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
}

代码解释如下:

  • ① 获取resultContext 然后跳到下一行(第一次next方法执行前指针位置是before start of resultset);
  • ② 如果有下一行记录需要处理并且有对应的resultSet,则进行迭代循环处理;
    • ③ 处理Discriminator;

    • ④ 获取RowValue也就是行记录返回值,这里是Employee对象。 在这里插入图片描述

    • storeObject方法会把当前context.getResultObject()放到DefaultResultHandler的成员List<Object> list

获取行记录返回结果方法如下所示:

private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
  final ResultLoaderMap lazyLoader = new ResultLoaderMap();
  //这里是空对象 空对象,在下面过程中会对其进行属性赋值
  Object resultObject = createResultObject(rsw, resultMap, lazyLoader, null);
  if (resultObject != null && !hasTypeHandlerForResultObject(rsw, resultMap.getType())) {
    final MetaObject metaObject = configuration.newMetaObject(resultObject);
    boolean foundValues = !resultMap.getConstructorResultMappings().isEmpty();
    if (shouldApplyAutomaticMappings(resultMap, false)) {
      foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
    }
    foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
    foundValues = lazyLoader.size() > 0 || foundValues;
    resultObject = foundValues ? resultObject : null;
    return resultObject;
  }
  return resultObject;
}

代码解释如下:

  • ① 获取返回结果对象resultObject ,这里得到的Employee是一个空对象,成员值都是null
  • ② 根据resultObject 获取MetaObject 对象;
  • ③ 判断是否可以进行自动映射(也就是查询返回的column与对象property一致),如果是则进行applyAutomaticMappings
  • ④ 尝试进行applyPropertyMappings,也就是自定义了resultMap,做了列与属性映射;
  • ⑤ 判断是返回null还是resultObject

处理完当前ResultSet后,会获取nextResultSet,将得到的结果存储起来。迭代处理完后,依次返回。其中这里应用了大量的代理模式、装饰模式以及mybatis结果映射的知识。另外,这里只是在单mybatis环境下对单个查询进行分析,那么在SSM、SpringBoot环境下的流程细节可能有所不同。


这里补充一下ResultSet、ResultSetImpl与NativeResultset获取数据的过程。

ResultSet是一个接口,我们代码中看到的也是一个代理对象(可能是多次代理哦,比如ResultSetImpl-HikariProxyResultSet-org.apache.ibatis.logging.jdbc.ResultSetLogger),其会将操作委派给ResultSetImpl去处理。

ResultSetImpl继承自NativeResultset,后者拥有属性ResultsetRows rowData维护了数据库查询的数据以及属性Row thisRow维护当前数据。每一次的resultSet.next()造成的结果就是this.thisRow = this.rowData.next();

rowData如下图所示,内维护了一个内部字节数组,存放每一行的非空属性。数组下标对应列定义下标。
在这里插入图片描述
那么列定义是什么?直接看图吧
在这里插入图片描述

rowData什么时候被赋值的?

在执行完数据库查询(或其他操作)后创建ResultSetImpl时为rowData赋值,多行结果集时rowData中rows有多个元素,如下图所示:
在这里插入图片描述
在这里插入图片描述

参考博文:
MyBatis中XML映射器使用详解
MyBatis中映射器之结果映射详解
设计模式之装饰者模式
设计模式之代理模式

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值