首页 > 数据库 >#yyds干货盘点#Mybatis如何执行SQL语句

#yyds干货盘点#Mybatis如何执行SQL语句

时间:2023-06-05 15:32:28浏览次数:41  
标签:yyds name args Param sqlSession 参数 SQL Mybatis method

mybatis 操作数据库的过程

// 第一步:读取mybatis-config.xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 第二步:构建SqlSessionFactory(框架初始化)
SqlSessionFactory sqlSessionFactory = new  SqlSessionFactoryBuilder().bulid();
// 第三步:打开sqlSession
SqlSession session = sqlSessionFactory.openSession();
// 第四步:获取Mapper接口对象(底层是动态代理)
AccountMapper accountMapper = session.getMapper(AccountMapper.class);
// 第五步:调用Mapper接口对象的方法操作数据库;
Account account = accountMapper.selectByPrimaryKey(1);

通过调用 session.getMapper (AccountMapper.class) 所得到的 AccountMapper 是一个动态代理对象,所以执行

accountMapper.selectByPrimaryKey (1) 方法前,都会被 invoke () 拦截,先执行 invoke () 中的逻辑。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //  要执行的方法所在的类如果是Object,直接调用,不做拦截处理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
            //如果是默认方法,也就是java8中的default方法
        } else if (isDefaultMethod(method)) {
            // 直接执行default方法
            return invokeDefaultMethod(proxy, method, args);
        }
    } catch (Throwable t) {
        throw ExceptionUtil.unwrapThrowable(t);
    } 
    // 从缓存中获取MapperMethod
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
}

从 methodCache 获取对应 DAO 方法的 MapperMethod

MapperMethod 的主要功能是执行 SQL 语句的相关操作,在初始化的时候会实例化两个对象:SqlCommand(Sql 命令)和 MethodSignature(方法签名)。

/**
   * 根据Mapper接口类型、接口方法、核心配置对象 构造MapperMethod对象
   * @param mapperInterface
   * @param method
   * @param config
   */
  public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new SqlCommand(config, mapperInterface, method);
    // 将Mapper接口中的数据库操作方法(如Account selectById(Integer id);)封装成方法签名MethodSignature
    this.method = new MethodSignature(config, mapperInterface, method);
  }

new SqlCommand()调用 SqlCommand 类构造方法:

public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
      // 获取Mapper接口中要执行的某个方法的方法名
      // 如accountMapper.selectByPrimaryKey(1)
      final String methodName = method.getName();
      // 获取方法所在的类
      final Class<?> declaringClass = method.getDeclaringClass();
      // 解析得到Mapper语句对象(对配置文件中的<mapper></mapper>中的sql语句进行封装)
      MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
          configuration);
      if (ms == null) {
        if (method.getAnnotation(Flush.class) != null) {
          name = null;
          type = SqlCommandType.FLUSH;
        } else {
          throw new BindingException("Invalid bound statement (not found): "
              + mapperInterface.getName() + "." + methodName);
        }
      } else {
        // 如com.bjpowernode.mapper.AccountMapper.selectByPrimaryKey
        name = ms.getId();
        // SQL类型:增 删 改 查
        type = ms.getSqlCommandType();
        if (type == SqlCommandType.UNKNOWN) {
          throw new BindingException("Unknown execution method for: " + name);
        }
      }
    }
private MapperMethod cachedMapperMethod(Method method) {
     MapperMethod mapperMethod = (MapperMethod)this.methodCache.get(method);
     if (mapperMethod == null) {
         mapperMethod = new MapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration());
         this.methodCache.put(method, mapperMethod);
     }
     return mapperMethod;
 }

调用 mapperMethod.execute (sqlSession, args)

在 mapperMethod.execute () 方法中,我们可以看到:mybatis 定义了 5 种 SQL 操作类型:
insert/update/delete/select/flush。其中,select 操作类型又可以分为五类,这五类的返回结果都不同,分别对应:

・返回参数为空:executeWithResultHandler ();

・查询多条记录:executeForMany (),返回对象为 JavaBean

・返参对象为 map:executeForMap (), 通过该方法查询数据库,最终的返回结果不是 JavaBean,而是 Map

・游标查询:executeForCursor ();关于什么是游标查询,自行百度哈;

・查询单条记录: sqlSession.selectOne (),通过该查询方法,最终只会返回一条结果;

通过源码追踪我们可以不难发现:当调用 mapperMethod.execute () 执行 SQL 语句的时候,无论是
insert/update/delete/flush,还是 select(包括 5 种不同的 select), 本质上时通过 sqlSession 调用的。在 SELECT 操作中,虽然调用了 MapperMethod 中的方法,但本质上仍是通过 Sqlsession 下的 select (), selectList (), selectCursor (), selectMap () 等方法实现的。

而 SqlSession 的内部实现,最终是调用执行器 Executor(后面会细说)。这里,我们可以先大概看一下 mybatis 在执行 SQL 语句的时候的调用过程:

#yyds干货盘点#Mybatis如何执行SQL语句_动态代理

以accountMapper.selectByPrimaryKey (1) 为例:

・调用 SqlSession.getMapper ():得到 xxxMapper (如 UserMapper) 的动态代理对象;

・调用
accountMapper.selectByPrimaryKey (1):在 xxxMapper 动态代理内部,会根据要执行的 SQL 语句类型 (insert/update/delete/select/flush) 来调用 SqlSession 对应的不同方法,如 sqlSession.insert ();

・在 sqlSession.insert () 方法的实现逻辑中,又会转交给 executor.query () 进行查询;

・executor.query () 又最终会转交给 statement 类进行操作,到这里就是 jdbc 操作了。

有人会好奇,为什么要通过不断的转交,SqlSession->Executor->Statement,而不是直接调用 Statement 执行 SQL 语句呢?因为在调用 Statement 之前,会处理一些共性的逻辑,如在 Executor 的实现类 BaseExecutor 会有一级缓存相关的逻辑,在 CachingExecutor 中会有二级缓存的相关逻辑。如果直接调用 Statement 执行 SQL 语句,那么在每个 Statement 的实现类中,都要写一套一级缓存和二级缓存的逻辑,就显得冗余了。这一块后面会细讲。

// SQL命令(在解析mybatis-config.xml配置文件的时候生成的)
  private final SqlCommand command;
  
  public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    // 从command对象中获取要执行操作的SQL语句的类型,如INSERT/UPDATE/DELETE/SELECT
    switch (command.getType()) {
      // 插入
      case INSERT: {
        // 把接口方法里的参数转换成sql能识别的参数
        // 如:accountMapper.selectByPrimaryKey(1)
        // 把其中的参数"1"转化为sql能够识别的参数
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 调用SqlSession执行插入操作
        // rowCountResult(): 获取SQL语句的执行结果
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      // 更新
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 调用SqlSession执行更新操作
        // rowCountResult(): 获取SQL语句的执行结果
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      // 删除
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        // sqlSession.insert(): 调用SqlSession执行更新操作
        // rowCountResult(): 获取SQL语句的执行结果
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      // 查询
      case SELECT:
        // method.returnsVoid(): 返参是否为void
        // method.hasResultHandler(): 是否有对应的结果处理器
        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()) { // 以游标的方式进行查询
          result = executeForCursor(sqlSession, args);
        } else {
          // 参数转换 转成sqlCommand参数
          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;
  }

在上面,有多处出现这样一行代码:
method.convertArgsToSqlCommandParam (args),该方法的作用就是将方法参数转换为 SqlCommandParam;具体交由
paramNameResolver.getNamedParams () 实现。在看 paramNameResolver.getNamedParams () 之前,我们先来看下 paramNameResolver 是什么东西?

public Object convertArgsToSqlCommandParam(Object[] args) {
      return paramNameResolver.getNamedParams(args);
    }

在前面,我们在实例化 MethodSignature 对象 (new MethodSignature) 的时候,在其构造方法中,会实例化 ParamNameResolver 对象,该对象主要用来处理接口形式的参数,最后会把参数处放在一个 map(即属性 names)中。map 的 key 为参数的位置,value 为参数的名字。

public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
  ...
  this.paramNameResolver = new ParamNameResolver(configuration, method);
}

对 names 字段的解释:

假设在 xxxMapper 中有这么一个接口方法 selectByIdAndName ()

・selectByIdAndName (@Param ("id") String id, @Param ("name") String name) 转化为 map 为 {{0, "id"}, {1, "name"}}

・selectByIdAndName (String id, String name) 转化为 map 为 {{0, "0"}, {1, "1"}}

・selectByIdAndName (int a, RowBounds rb, int b) 转化为 map 为 {{0, "0"}, {2, "1"}}

构造方法的会经历如下的步骤

  1. 通过反射得到方法的参数类型和方法的参数注解注解,
    method.getParameterAnnotations () 方法返回的是注解的二维数组,每一个方法的参数包含一个注解数组。
  2. 遍历所有的参数
  • 首先判断这个参数的类型是否是特殊类型,RowBounds 和 ResultHandler,是的话跳过,咱不处理
  • 判断这个参数是否是用来 Param 注解,如果使用的话 name 就是 Param 注解的值,并把 name 放到 map 中,键为参数在方法中的位置,value 为 Param 的值
  • 如果没有使用 Param 注解,判断是否开启了 UseActualParamName,如果开启了,则使用 java8 的反射得到方法的名字,此处容易造成异常,

具体原因参考上一篇博文.

  • 如果以上条件都不满足的话,则这个参数的名字为参数的下标
// 通用key前缀,因为key有param1,param2,param3等;
  public static final String GENERIC_NAME_PREFIX = "param";
  // 存放参数的位置和对应的参数名
  private final SortedMap<Integer, String> names;
  // 是否使用@Param注解
  private boolean hasParamAnnotation;

  public ParamNameResolver(Configuration config, Method method) {
    // 通过注解得到方法的参数类型数组
    final Class<?>[] paramTypes = method.getParameterTypes();
    // 通过反射得到方法的参数注解数组
    final Annotation[][] paramAnnotations = method.getParameterAnnotations();
    // 用于存储所有参数名的SortedMap对象
    final SortedMap<Integer, String> map = new TreeMap<>();
    // 参数注解数组长度,即方法入参中有几个地方使用了@Param
    // 如selectByIdAndName(@Param("id") String id, @Param("name") String name)中,paramCount=2
    int paramCount = paramAnnotations.length;
    // 遍历所有的参数
    for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
      // 判断这个参数的类型是否是特殊类型,RowBounds和ResultHandler,是的话跳过
      if (isSpecialParameter(paramTypes[paramIndex])) {
        continue;
      }
      String name = null;
      for (Annotation annotation : paramAnnotations[paramIndex]) {
        // 判断这个参数是否使用了@Param注解
        if (annotation instanceof Param) {
          // 标记当前方法使用了Param注解
          hasParamAnnotation = true;
          // 如果使用的话name就是Param注解的值
          name = ((Param) annotation).value();
          break;
        }
      }
      // 如果经过上面处理,参数名还是null,则说明当前参数没有指定@Param注解
      if (name == null) {
        // 判断是否开启了UseActualParamName
        if (config.isUseActualParamName()) {
          // 如果开启了,则使用java8的反射得到该参数对应的属性名
          name = getActualParamName(method, paramIndex);
        }
        // 如果name还是为null
        if (name == null) {
          // use the parameter index as the name ("0", "1", ...)
          // 使用参数在map中的下标作为参数的name,如 ("0", "1", ...)
          name = String.valueOf(map.size());
        }
      }
      // 把参数放入到map中,key为参数在方法中的位置,value为参数的name(@Param的value值/参数对应的属性名/参数在map中的位置下标)
      map.put(paramIndex, name);
    }
    // 最后使用Collections工具类的静态方法将结果map变为一个不可修改类型
    names = Collections.unmodifiableSortedMap(map);
  }

getNamedParams(): 该方法会将参数名和参数值对应起来,并且还会额外保存一份以 param 开头加参数顺序数字的值

public Object getNamedParams(Object[] args) {
    // 这里的names就是ParamNameResolver中的names,在构造ParamNameResolver对象的时候,创建了该Map
    // 获取方法参数个数
    final int paramCount = names.size();
    // 没有参数
    if (args == null || paramCount == 0) {
      return null;
    // 只有一个参数,并且没有使用@Param注解。
    } else if (!hasParamAnnotation && paramCount == 1) {
      // 直接返回,不做任务处理
      return args[names.firstKey()];
    } else {
      // 包装成ParamMap对象。这个对象继承了HashMap,重写了get方法。
      final Map<String, Object> param = new ParamMap<>();
      int i = 0;
      // 遍历names中的所有键值对
      for (Map.Entry<Integer, String> entry : names.entrySet()) {
        // 将参数名作为key, 对应的参数值作为value,放入结果param对象中
        param.put(entry.getValue(), args[entry.getKey()]);
        // 用于添加通用的参数名称,按顺序命名(param1, param2, ...)
        final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
        // 确保不覆盖以@Param 命名的参数
        if (!names.containsValue(genericParamName)) {
          param.put(genericParamName, args[entry.getKey()]);
        }
        i++;
      }
      return param;
    }
  }
}

getNamedParams () 总结:

  1. 当只有一个参数的时候,直接返回,不做任务处理;
  2. 否则,存入 Map 中,键值对形式为:paramName=paramValue

・selectByIdAndName (@Param ("id") String id, @Param ("name") String name): 传入的参数是 ["1", "张三"],最后解析出来的 map 为:{“id”:”1”,”“name”:” 张三”}

・selectByIdAndName (String id, @Param ("name") String name): 传入的参数是 ["1", "张三"],最后解析出来的 map 为:{“param1”:”1”,”“name”:” 张三”}

假设执行的 SQL 语句是 select 类型,继续往下看代码

在 mapperMethod.execute (), 当
convertArgsToSqlCommandParam () 方法处理完方法参数后,假设我们此时调用的是查询单条记录,那么接下来会执行 sqlSession.selectOne () 方法。

sqlSession.selectOne () 源码分析:

sqlSession.selectOne () 也是调的 sqlSession.selectList () 方法,只不过只返回 list 中的第一条数据。当 list 中有多条数据时,抛异常。

@Override
public <T> T selectOne(String statement, Object parameter) {
  // 调用当前类的selectList方法
  List<T> 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;
  }
}

sqlSession.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 {
      // 从Configuration里的mappedStatements里根据key(id的全路径)获取MappedStatement对象
      MappedStatement ms = configuration.getMappedStatement(statement);
      // 调用Executor的实现类BaseExecutor的query()方法
      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();
    }
  }

在 sqlSession.selectList () 方法中,我们可以看到调用了 executor.query (),假设我们开启了二级缓存,那么 executor.query () 调用的是 executor 的实现类 CachingExecutor 中的 query (),二级缓存的逻辑就是在 CachingExecutor 这个类中实现的。

标签:yyds,name,args,Param,sqlSession,参数,SQL,Mybatis,method
From: https://blog.51cto.com/u_11365839/6416570

相关文章

  • Mysql:事务
    事务特性事务的特性:acid。原子性(重要)事务内的一组操作为原子操作,要么全部成功,要么全部失败。在实际业务如转账,就必须保证一方数目多了一方少了,数目平衡。一致性(面试常问)事务成功或失败的结果必须符合业务逻辑。还是以转账为例,A转给B100块,成功就A少100,B多100,失败就双方金额该......
  • pymysql.err.DataError: (1366, “Incorrect string value: ‘\\xF0\\x9F\\x92
    原因是字符串中有emoji数据。原因:字符串中有emoji字符,数据库是utf8无法识别解决方法:安装emoji库pipinstallemoji处理字符串:importemojis=emoji.demojize('......
  • 汇总低效的SQL语句
    背景SQL专家云像“摄像头”一样,对环境、参数配置、服务器性能指标、活动会话、慢语句、磁盘空间、数据库文件、索引、作业、日志等几十个运行指标进行不同频率的实时采集,保存到SQL专家云自己的数据库中。因此可以随时对任何一个时间段内的SQL语句进行汇总,找到低效的SQL语句。慢......
  • mybatis-plus扩展extend批量操作(自带批量操作是循环单条插入,效率太低)
    目录添加依赖构建三个配置-推荐放一个包里面让原本继承BaseMapper<实体>的Dao层改为继承EasyBaseMapper<实体>service层已经可以使用批量操作了 添加依赖<!--mybatis-plus组件--><dependency><groupId>com.baomidou</groupId><artifactId>myba......
  • 递归SQL的写法
     1.递归查询某一节点的无限级子集(不含自身)。#功能:递归查询某一节点的无限级子集。#参数说明:#表名:organization#父ID字段:parent_id#主键ID字段:id#顶层ID值:1604SELECT *FROM (SELECT*FROMorganization)A, (SELECT@pv:='1604')BWHERE find_in_set(......
  • Docker-compose一键部署安装confluence+sql数据库(附数据迁移方法)
    Docker-compose部署安装confluence并进行数据迁移 目录Docker-compose部署安装confluence并进行数据迁移一、部署confluence和postgresql二、激活confluence三、confluence数据迁移恢复 一、部署confluence和postgresql下载confluence镜像和postgresql镜像资......
  • mysql数据自动备份脚本
    #!/bin/bash#日期date=$(date'+%Y%m%d')#设置备份目录和保留天数backup_dir="/opt/dbback"retention_days=7#数据库账密muser=mpasswd=mhost=#创建备份目录(如果不存在)mkdir-p$backup_dir#获取当前时间戳now=$(date+%s)#备份MySQL数据库到备份目......
  • MySQL数据库表结构优化方式详解
    前言从今天开始本系列文章就带各位小伙伴学习数据库技术。数据库技术是Java开发中必不可少的一部分知识内容。也是非常重要的技术。本系列教程由浅入深,全面讲解数据库体系。非常适合零基础的小伙伴来学习。全文大约【2083】字,不说废话,只讲可以让你学到技术、明白原理的纯干......
  • SQL注入三连实战绕过WTS-WAF
    一键三连,sql注入一次无意之间发现的sql注入,主要是因为有一个WTS-WAF,在此记录一下只是友好测试,并非有意为之。。。。牛刀小试1手注判断字段数测试到orderby15的时候出现了报错,那么就可以说明字段数为14http://www.xxx.com/xxx.php?id=22%20order%20by%2014http://www.x......
  • ORM核心功能之导航属性- EFCore和 SqlSugar
    导航属性导航属性是作为ORM核心功能中的核心,在SqlSugar没有支持导航属性前,都说只是一个高级DbHelper,经过3年的SqlSugar重构已经拥有了一套非常成熟的导航属性体系,本文不是重点讲SqlSugar而是重点讲导航属性的作用,让更多写Sql人还未使用ORM的人了解到ORM的作用。 1.复杂的查......