手把手带你阅读Mybatis源码(二)执行篇(上)

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
简介: 手把手带你阅读Mybatis源码(二)执行篇(上)

前言


上一篇文章提到了MyBatis是如何构建配置类的,也说了MyBatis在运行过程中主要分为两个阶段,第一是构建,第二就是执行,所以这篇文章会带大家来了解一下MyBatis是如何从构建完毕,到执行我们的第一条SQL语句的。之后这部分内容会归置到公众号菜单栏:连载中…-框架分析中,欢迎探讨!


入口(代理对象的生成)


public static void main(String[] args) throws Exception {
    /******************************构造******************************/
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //创建SqlSessionFacory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    /******************************分割线******************************/
    /******************************执行******************************/
    //SqlSession是帮我们操作数据库的对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //获取Mapper
    DemoMapper mapper = sqlSession.getMapper(DemoMapper.class);
    Map<String,Object> map = new HashMap<>();
    map.put("id","123");
    System.out.println(mapper.selectAll(map));
    sqlSession.close();
    sqlSession.commit();
  }


首先在没看源码之前希望大家可以回忆起来,我们在使用原生MyBatis的时候(不与Spring进行整合),操作SQL的只需要一个对象,那就是SqlSession对象,这个对象就是专门与数据库进行交互的。


我们在构造篇有提到,Configuration对象是在SqlSessionFactoryBuilder中的build方法中调用了XMLConfigBuilder的parse方法进行解析的,但是我们没有提到这个Configuration最终的去向。讲这个之前我们可以思考一下,这个Configuration生成之后,会在哪个环节被使用?毋庸置疑,它作为一个配置文件的整合,里面包含了数据库连接相关的信息,SQL语句相关信息等,在查询的整个流程中必不可少,而刚才我们又说过,SqlSession实际上是我们操作数据库的一个真实对象,所以可以得出这个结论:


Configuration必然和SqlSession有所联系。


源码:


public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //解析config.xml(mybatis解析xml是用的  java dom)     dom4j sax...
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //parse(): 解析config.xml里面的节点
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
}
public SqlSessionFactory build(Configuration config) {
      //注入到SqlSessionFactory
    return new DefaultSqlSessionFactory(config);
}
public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
}


实际上我们从源码中可以看到,Configuration是SqlSessionFactory的一个属性,而SqlSessionFactoryBuilder在build方法中实际上就是调用XMLConfigBuilder对xml文件进行解析,然后注入到SqlSessionFactory中。


image.png


明确了这一点我们就接着往下看。


根据主线我们现在得到了一个SqlSessionFactory对象,下一步就是要去获取SqlSession对象,这里会调用SqlSessionFactory.openSession()方法来获取,而openSession中实际上就是对SqlSession做了进一步的加工封装,包括增加了事务、执行器等。


private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
        //对SqlSession对象进行进一步加工封装
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      final Executor executor = configuration.newExecutor(tx, execType);
        //构建SqlSession对象
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } 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();
    }
  }


到这里可以得出的小结论是,SqlSessionFactory对象中由于存在Configuration对象,所以它保存了全局配置信息,以及初始化环境和DataSource,而DataSource的作用就是用来开辟链接,当我们调用openSession方法时,就会开辟一个连接对象并传给SqlSession对象,交给SqlSession来对数据库做相关操作


接着往下,现在我们获取到了一个SqlSession对象,而执行过程就是从这里开始的。


我们可以开始回忆了,平时我们使用MyBatis的时候,我们写的DAO层应该长这样:


public interface DemoMapper {
  public List<Map<String,Object>>  selectAll(Map<String,Object> map);
}


实际上它是一个接口,而且并没有实现类,而我们却可以直接对它进行调用,如下:


DemoMapper mapper = sqlSession.getMapper(DemoMapper.class);
 Map<String,Object> map = new HashMap();
 map.put("id","123");
 System.out.println(mapper.selectAll(map));


可以猜测了,MyBatis底层一定使用了动态代理,来对这个接口进行代理,我们实际上调用的是MyBatis为我们生成的代理对象。


我们在获取Mapper的时候,需要调用SqlSession的getMapper()方法,那么就从这里深入。


//getMapper方法最终会调用到这里,这个是MapperRegistry的getMapper方法
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
      //MapperProxyFactory  在解析的时候会生成一个map  map中会有我们的DemoMapper的Class
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) 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);
    }
}


可以看到这里mapperProxyFactory对象会从一个叫做knownMappers的对象中以type为key取出值,这个knownMappers是一个HashMap,存放了我们的DemoMapper对象,而这里的type,就是我们上面写的Mapper接口。那么就有人会问了,这个knownMappers是在什么时候生成的呢?实际上这是我上一篇漏讲的一个地方,在解析的时候,会调用parse()方法,相信大家都还记得,这个方法内部有一个bindMapperForNamespace方法,而就是这个方法帮我们完成了knownMappers的生成,并且将我们的Mapper接口put进去。


public void parse() {
      //判断文件是否之前解析过
    if (!configuration.isResourceLoaded(resource)) {
        //解析mapper文件
      configurationElement(parser.evalNode("/mapper"));
      configuration.addLoadedResource(resource);
      //这里:绑定Namespace里面的Class对象*
      bindMapperForNamespace();
    }
    //重新解析之前解析不了的节点
    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
  }
private void bindMapperForNamespace() {
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
      Class<?> boundType = null;
      try {
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {
      }
      if (boundType != null) {
        if (!configuration.hasMapper(boundType)) {
          configuration.addLoadedResource("namespace:" + namespace);
            //这里将接口class传入
          configuration.addMapper(boundType);
        }
      }
    }
  }
public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {
      if (hasMapper(type)) {
        throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
      }
      boolean loadCompleted = false;
      try {
          //这里将接口信息put进konwMappers。
        knownMappers.put(type, new MapperProxyFactory<>(type));
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
}


所以我们在getMapper之后,获取到的是一个Class,之后的代码就简单了,就是生成标准的代理类了,调用newInstance()方法。


public T newInstance(SqlSession sqlSession) {
    //首先会调用这个newInstance方法
    //动态代理逻辑在MapperProxy里面
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    //通过这里调用下面的newInstance方法
    return newInstance(mapperProxy);
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
     //jdk自带的动态代理
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}


到这里,就完成了代理对象MapperProxy)的创建,很明显的,MyBatis的底层就是对我们的接口进行代理类的实例化,从而操作数据库。


但是,我们好像就得到了一个空荡荡的对象,调用方法的逻辑呢?好像根本就没有看到,所以这也是比较考验Java功底的地方。


我们知道,一个类如果要称为代理对象,那么一定需要实现InvocationHandler接口,并且实现其中的invoke方法,进行一波推测,逻辑一定在invoke方法中。


于是就可以点进MapperProxy类,发现其的确实现了InvocationHandler接口,这里我将一些用不到的代码先删除了,只留下有用的代码,便于分析


/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {
  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
      //构造
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    //这就是一个很标准的JDK动态代理了
    //执行的时候会调用invoke方法
    try {
      if (Object.class.equals(method.getDeclaringClass())) {
          //判断方法所属的类
          //是不是调用的Object默认的方法
          //如果是  则不代理,不改变原先方法的行为
        return method.invoke(this, args);
      } else if (method.isDefault()) {
          //对于默认方法的处理
          //判断是否为default方法,即接口中定义的默认方法。
          //如果是接口中的默认方法则把方法绑定到代理对象中然后调用。
          //这里不详细说
        if (privateLookupInMethod == null) {
          return invokeDefaultMethodJava8(proxy, method, args);
        } else {
          return invokeDefaultMethodJava9(proxy, method, args);
        }
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //如果不是默认方法,则真正开始执行MyBatis代理逻辑。
    //获取MapperMethod代理对象
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //执行
    return mapperMethod.execute(sqlSession, args);
  }
  private MapperMethod cachedMapperMethod(Method method) {
      //动态代理会有缓存,computeIfAbsent 如果缓存中有则直接从缓存中拿
      //如果缓存中没有,则new一个然后放入缓存中
      //因为动态代理是很耗资源的
    return methodCache.computeIfAbsent(method,
        k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
  }
}


在方法开始代理之前,首先会先判断是否调用了Object类的方法,如果是,那么MyBatis不会去改变其行为,直接返回,如果是默认方法,则绑定到代理对象中然后调用(不是本文的重点),如果都不是,那么就是我们定义的mapper接口方法了,那么就开始执行。

执行方法需要一个MapperMethod对象,这个对象是MyBatis执行方法逻辑使用的,MyBatis这里获取MapperMethod对象的方式是,首先去方法缓存中看看是否已经存在了,如果不存在则new一个然后存入缓存中,因为创建代理对象是十分消耗资源的操作。总而言之,这里会得到一个MapperMethod对象,然后通过MapperMethod的excute()方法,来真正地执行逻辑。


执行逻辑


语句类型判断


这里首先会判断SQL的类型:SELECT|DELETE|UPDATE|INSERT,我们这里举的例子是SELECT,其它的其实都差不多,感兴趣的同学可以自己去看看。判断SQL类型为SELECT之后,就开始判断返回值类型,根据不同的情况做不同的操作。然后开始获取参数--》执行SQL。


//execute() 这里是真正执行SQL的地方
  public Object execute(SqlSession sqlSession, Object[] args) {
      //判断是哪一种SQL语句
      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()) {
              //返回Map
            result = executeForMap(sqlSession, args);
          } else if (method.returnsCursor()) {
              //返回Cursor
            result = executeForCursor(sqlSession, args);
          } else {
            Object param = method.convertArgsToSqlCommandParam(args);
            result = sqlSession.selectOne(command.getName(), param);
            if (method.returnsOptional()
                && (result == null || !method.getReturnType().equals(result.getClass()))) {
              result = Optional.ofNullable(result);
            }
          }
          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;
  }
  //返回值多行 这里调用这个方法
  private <E> Object executeForMany(SqlSession sqlSession, Object[] args) {
      //返回值多行时执行的方法
      List<E> result;
      //param是我们传入的参数,如果传入的是Map,那么这个实际上就是Map对象
      Object param = method.convertArgsToSqlCommandParam(args);
      if (method.hasRowBounds()) {
          //如果有分页
        RowBounds rowBounds = method.extractRowBounds(args);
          //执行SQL的位置
        result = sqlSession.selectList(command.getName(), param, rowBounds);
      } else {
          //如果没有
          //执行SQL的位置
        result = sqlSession.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 Object getNamedParams(Object[] args) {
      final int paramCount = names.size();
      if (args == null || paramCount == 0) {
          //如果传过来的参数是空
        return null;
      } else if (!hasParamAnnotation && paramCount == 1) {
          //如果参数上没有加注解例如@Param,且参数只有一个,则直接返回参数
        return args[names.firstKey()];
      } else {
          //如果参数上加了注解,或者参数有多个。
            //那么MyBatis会封装参数为一个Map,但是要注意,由于jdk的原因,我们只能获取到参数下标和参数名,但是参数名会变成arg0,arg1.
          //所以传入多个参数的时候,最好加@Param,否则假设传入多个String,会造成#{}获取不到值的情况
        final Map<String, Object> param = new ParamMap<>();
        int i = 0;
        for (Map.Entry<Integer, String> entry : names.entrySet()) {
            //entry.getValue 就是参数名称
          param.put(entry.getValue(), args[entry.getKey()]);
          //如果传很多个String,也可以使用param1,param2.。。
          // 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;
      }
    }


相关文章
|
16天前
|
SQL XML Java
mybatis-源码深入分析(一)
mybatis-源码深入分析(一)
|
1天前
|
前端开发 Java 数据库连接
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
本文是一份全面的表白墙/留言墙项目教程,使用SpringBoot + MyBatis技术栈和MySQL数据库开发,涵盖了项目前后端开发、数据库配置、代码实现和运行的详细步骤。
6 0
表白墙/留言墙 —— 中级SpringBoot项目,MyBatis技术栈MySQL数据库开发,练手项目前后端开发(带完整源码) 全方位全步骤手把手教学
|
2天前
|
Java 数据库连接 mybatis
Springboot整合Mybatis,MybatisPlus源码分析,自动装配实现包扫描源码
该文档详细介绍了如何在Springboot Web项目中整合Mybatis,包括添加依赖、使用`@MapperScan`注解配置包扫描路径等步骤。若未使用`@MapperScan`,系统会自动扫描加了`@Mapper`注解的接口;若使用了`@MapperScan`,则按指定路径扫描。文档还深入分析了相关源码,解释了不同情况下的扫描逻辑与优先级,帮助理解Mybatis在Springboot项目中的自动配置机制。
Springboot整合Mybatis,MybatisPlus源码分析,自动装配实现包扫描源码
|
2月前
|
XML Java 数据库连接
mybatis源码研究、搭建mybatis源码运行的环境
这篇文章详细介绍了如何搭建MyBatis源码运行的环境,包括创建Maven项目、导入源码、添加代码、Debug运行研究源码,并提供了解决常见问题的方法和链接到搭建好的环境。
mybatis源码研究、搭建mybatis源码运行的环境
|
2月前
|
Web App开发 前端开发 关系型数据库
基于SpringBoot+Vue+Redis+Mybatis的商城购物系统 【系统实现+系统源码+答辩PPT】
这篇文章介绍了一个基于SpringBoot+Vue+Redis+Mybatis技术栈开发的商城购物系统,包括系统功能、页面展示、前后端项目结构和核心代码,以及如何获取系统源码和答辩PPT的方法。
|
2月前
|
供应链 前端开发 Java
服装库存管理系统 Mybatis+Layui+MVC+JSP【完整功能介绍+实现详情+源码】
该博客文章介绍了一个使用Mybatis、Layui、MVC和JSP技术栈开发的服装库存管理系统,包括注册登录、权限管理、用户和货号管理、库存管理等功能,并提供了源码下载链接。
服装库存管理系统 Mybatis+Layui+MVC+JSP【完整功能介绍+实现详情+源码】
|
2月前
|
缓存 Java 数据库连接
我要手撕mybatis源码
该文章深入分析了MyBatis框架的初始化和数据读写阶段的源码,详细阐述了MyBatis如何通过配置文件解析、建立数据库连接、映射接口绑定、动态代理、查询缓存和结果集处理等步骤实现ORM功能,以及与传统JDBC编程相比的优势。
我要手撕mybatis源码
|
26天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
13天前
|
SQL XML Java
springboot整合mybatis-plus及mybatis-plus分页插件的使用
这篇文章介绍了如何在Spring Boot项目中整合MyBatis-Plus及其分页插件,包括依赖引入、配置文件编写、SQL表创建、Mapper层、Service层、Controller层的创建,以及分页插件的使用和数据展示HTML页面的编写。
springboot整合mybatis-plus及mybatis-plus分页插件的使用
|
2月前
|
Java 数据库连接 测试技术
SpringBoot 3.3.2 + ShardingSphere 5.5 + Mybatis-plus:轻松搞定数据加解密,支持字段级!
【8月更文挑战第30天】在数据驱动的时代,数据的安全性显得尤为重要。特别是在涉及用户隐私或敏感信息的应用中,如何确保数据在存储和传输过程中的安全性成为了开发者必须面对的问题。今天,我们将围绕SpringBoot 3.3.2、ShardingSphere 5.5以及Mybatis-plus的组合,探讨如何轻松实现数据的字段级加解密,为数据安全保驾护航。
117 1

相关实验场景

更多