MyBatis相关流程 源码分析

MyBatis的主要成员

  • Configuration MyBatis所有的配置信息都保存在Configuration对象之中,配置文件中的大部分配置都会存储到该类中
  • SqlSession 作为MyBatis工作的主要顶层API,表示和数据库交互时的会话,完成必要数据库增删改查功能
  • Executor MyBatis执行器,是MyBatis 调度的核心,负责SQL语句的生成和查询缓存的维护
  • StatementHandler 封装了JDBC Statement操作,负责对JDBC statement 的操作,如设置参数等
  • ParameterHandler 负责对用户传递的参数转换成JDBC Statement 所对应的数据类型
  • ResultSetHandler 负责将JDBC返回的ResultSet结果集对象转换成List类型的集合
  • TypeHandler 负责java数据类型和jdbc数据类型(也可以说是数据表列类型)之间的映射和转换
  • MappedStatement MappedStatement维护一条<select|update|delete|insert>节点的封装
  • SqlSource 负责根据用户传递的parameterObject,动态地生成SQL语句,将信息封装到BoundSql对象中,并返回
  • BoundSql 表示动态生成的SQL语句以及相应的参数信息

以上主要成员在一次数据库操作中基本都会涉及,在SQL操作中重点需要关注的是SQL参数什么时候被设置和结果集怎么转换为JavaBean对象的,这两个过程正好对应StatementHandler和ResultSetHandler类中的处理逻辑。

mybatis的初始化

MyBatis的初始化的过程其实就是解析mybatis-config.xml文件和初始化Configuration的过程。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SWNJJ27R-1600857664838)(C:\Users\Administrator.DESKTOP-SBF362H\AppData\Roaming\Typora\typora-user-images\image-20200922170356051.png)]

spring后置处理器处理SqlSessionFactory,因为在xml配置中,SqlSessionFactory是由spring进行管理,从这里入口,即可看到Configuration的初始化,也就是mybatis的初始化。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gBshwasC-1600857664842)(C:\Users\Administrator.DESKTOP-SBF362H\AppData\Roaming\Typora\typora-user-images\image-20200922172519904.png)]

xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
configuration = xmlConfigBuilder.getConfiguration();

通过流和XPath相关解析技术,解析配置文件,最后从xmlConfigBuilder获取到解析后配置好的configuration对象;

然后是注册别名信息,

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-joM8813H-1600857664844)(C:\Users\Administrator.DESKTOP-SBF362H\AppData\Roaming\Typora\typora-user-images\image-20200922173825196.png)]

如果有插件 就会添加插件信息。

最后是日志

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4zxxzyd1-1600857664849)(C:\Users\Administrator.DESKTOP-SBF362H\AppData\Roaming\Typora\typora-user-images\image-20200922173952408.png)]

最后是解析对应mapper下的文件xml。

private void configurationElement(XNode context) {
  try {
    String namespace = context.getStringAttribute("namespace");
    if (namespace.equals("")) {
     throw new BuilderException("Mapper's namespace cannot be empty");
    }
    builderAssistant.setCurrentNamespace(namespace);
    cacheRefElement(context.evalNode("cache-ref"));
    cacheElement(context.evalNode("cache"));
    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
    resultMapElements(context.evalNodes("/mapper/resultMap"));
    sqlElement(context.evalNodes("/mapper/sql"));
    buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
  }
}

重点看下最后一个方法解析sql语句,buildStatementFromContext,

继续跟踪代码就会发现

一个id属性就是sql文件的id 这个很有用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uFLpZcsZ-1600857664852)(C:\Users\Administrator.DESKTOP-SBF362H\AppData\Roaming\Typora\typora-user-images\image-20200922182040033.png)]

中间有类型相关的转化,最后

builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
    fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
    resultSetTypeEnum, flushCache, useCache, resultOrdered, 
    keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
id = applyCurrentNamespace(id, false);

id此时变成namespace+id

configuration.addMappedStatement(statement);

将动态sql进行缓存。

最后所有的都解析完,configuration配置完,mybatis的初始化工作就结束了。

SQL查询流程**

MyBatis的SQL查询流程

SQL语句的执行才是MyBatis的重要职责,该过程就是通过封装JDBC进行操作,然后使用Java反射技术完成JavaBean对象到数据库参数之间的相互转换,这种映射关系就是有TypeHandler对象来完成的,在获取数据表对应的元数据时,会保存该表所有列的数据库类型,大致逻辑如下所示:

我们可以在dao层打个断点进去看

首先会进入代理类

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  if (Object.class.equals(method.getDeclaringClass())) {
    return method.invoke(this, args);
  }
  final MapperMethod mapperMethod = cachedMapperMethod(method);
  return mapperMethod.execute(sqlSession, args);
}

mapper对应的代理是初始化时候已经注册到ioc容器中的,然后执行

execute
一文了解mybatis中动态代理的应用真相
https://blog.csdn.net/weixin_38738049/article/details/108742247

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 {
      Object param = method.convertArgsToSqlCommandParam(args);
      result = sqlSession.selectOne(command.getName(), param);
    }
  } 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;
}

以查询列表为例:

result = executeForMany(sqlSession, args);

这个方法继续跟踪

private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
  List<E> result;
  Object param = method.convertArgsToSqlCommandParam(args);//就是将Object[] args参数转化为map
  if (method.hasRowBounds()) {
    RowBounds rowBounds = method.extractRowBounds(args);
    result = sqlSession.<E>selectList(command.getName(), param, rowBounds);
  } else {
    result = sqlSession.<E>selectList(command.getName(), param);//查询列表方法
  }
  // issue #510 Collections & arrays support
  if (!method.getReturnType().isAssignableFrom(result.getClass())) {
    if (method.getReturnType().isArray()) {
      return convertToArray(result);
    } else {
      return convertToDeclaredCollection(sqlSession.getConfiguration(), result);
    }
  }
  return result;
}
public <E> List<E> selectList(String statement, Object parameter) {
  return this.sqlSessionProxy.<E> selectList(statement, parameter);
}
private class SqlSessionInterceptor implements InvocationHandler {
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    SqlSession sqlSession = getSqlSession(
        SqlSessionTemplate.this.sqlSessionFactory,
        SqlSessionTemplate.this.executorType,
        SqlSessionTemplate.this.exceptionTranslator);
    try {
      Object result = method.invoke(sqlSession, args);

这里又用到了代理的方法,我们看具体的实现。

selectList为sqlsession接口中的方法。mybatis的默认实现是DefaultSqlSession,方法如下invoke方法必然会执行到这里

public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    MappedStatement ms = configuration.getMappedStatement(statement);
    List<E> result = executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    return result;
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

如果有分页,拦截器先进行分页sql处理最后,然后在执行CachingExecutor

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);
      if (!dirty) {
        cache.getReadWriteLock().readLock().lock();
        try {
          @SuppressWarnings("unchecked")
          List<E> cachedList = (List<E>) cache.getObject(key);
          if (cachedList != null) return cachedList;
        } finally {
          cache.getReadWriteLock().readLock().unlock();
        }
      }
      List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
      tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
      return list;
    }
  }
  return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);//执行查询
}
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(this, ms, parameter, rowBounds, resultHandler, boundSql);
    stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}

stmt = prepareStatement(handler, ms.getStatementLog()); 方法中进行了相关的参数设置等操作。

最后就是我们最常见的

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

mybatis会将ResultHandler进行解析,返回为对应的list对象。

这里主要说下流程,细节就不展开说了。

总结:从流程可以看出,编写框架的所用的常用技术有xml解析,反射,动态代理,pagehelper中使用的拦截器也是通过动态代理实现分页处理。当我们不能直接处理目标方法时,就可以考虑使用动态代理来实现,aop的底层也是这样。当然还有一部分是通过cglib实现。
想要学习反射的朋友可以参考mybatis是如何用反射将数据库列和javabean映射的,ResultHandler解析也是同理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

晴天M雨天

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

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

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

打赏作者

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

抵扣说明:

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

余额充值