Mybatis 技术内幕:执行一个Sql命令的完整流程

简介: 如果不是使用Mapper接口调用,而是直接调用SqlSession的方法,那么,流程图从SqlSession的地方开始即可,后续都是一样的。

Mybatis中的Sql命令,在枚举类SqlCommandType中定义的。

public enum SqlCommandType {
   
  UNKNOWN, INSERT, UPDATE, DELETE, SELECT, FLUSH;
}

下面,我们以Mapper接口中的一个方法作为例子,看看Sql命令的执行完整流程。

public interface StudentMapper {
   
    List<Student> findAllStudents(Map<String, Object> map, RowBounds rowBounds, ResultSetHandler rh);    
}

参数RowBounds和ResultSetHandler是可选参数,表示分页对象和自定义结果集处理器,一般不需要。

一个完整的Sql命令,其执行的完整流程图如下:

一个完整的Sql命令,其执行的完整流程图如下.jpg

(Made In Edrawmax)

对于上面的流程图,如果看过前面的博文的话,大部分对象我们都比较熟悉了。一个图,就完整展示了其执行流程。

MapperProxy的功能:

  1. 因为Mapper接口不能直接实例化,MapperProxy的作用,就是使用JDK动态代理功能,间接实例化Mapper的proxy对象。可参看系列博文的第二篇。

  2. 缓存MapperMethod对象。

  private final Map<Method, MapperMethod> methodCache;
  @Override
  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);
      }
    }
    // 投鞭断流
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

  // 缓存MapperMethod
  private MapperMethod cachedMapperMethod(Method method) {
   
    MapperMethod mapperMethod = methodCache.get(method);
    if (mapperMethod == null) {
   
      mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
      methodCache.put(method, mapperMethod);
    }
    return mapperMethod;
  }

MapperMethod的功能:

  1. 解析Mapper接口的方法,并封装成MapperMethod对象。

  2. 将Sql命令,正确路由到恰当的SqlSession的方法上。

public class MapperMethod {
   

  // 保存了Sql命令的类型和键id
  private final SqlCommand command;
  // 保存了Mapper接口方法的解析信息
  private final MethodSignature method;

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

  // 根据解析结果,路由到恰当的SqlSession方法上
  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 if (SqlCommandType.FLUSH == command.getType()) {
   
        result = sqlSession.flushStatements();
    } 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;
  }
  // ...

org.apache.ibatis.binding.MapperMethod.SqlCommand。

public static class SqlCommand {
   
    // full id, 通过它可以找到MappedStatement
    private final String name;
    private final SqlCommandType type;
    // ...

org.apache.ibatis.binding.MapperMethod.MethodSignature。

  public static class MethodSignature {
   

    private final boolean returnsMany;
    private final boolean returnsMap;
    private final boolean returnsVoid;
    private final Class<?> returnType;
    private final String mapKey;
    private final Integer resultHandlerIndex;
    private final Integer rowBoundsIndex;
    private final SortedMap<Integer, String> params;
    private final boolean hasNamedParameters;

    public MethodSignature(Configuration configuration, Method method) {
   
      this.returnType = method.getReturnType();
      this.returnsVoid = void.class.equals(this.returnType);
      this.returnsMany = (configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray());
      this.mapKey = getMapKey(method);
      this.returnsMap = (this.mapKey != null);
      this.hasNamedParameters = hasNamedParams(method);
      // 分页参数
      this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
      // 自定义ResultHandler
      this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
      this.params = Collections.unmodifiableSortedMap(getParams(method, this.hasNamedParameters));
    }

以上是对MapperMethod的补充说明。

本节的重点,是上面的那个Sql命令完整执行流程图。如果不是使用Mapper接口调用,而是直接调用SqlSession的方法,那么,流程图从SqlSession的地方开始即可,后续都是一样的。

来源:https://my.oschina.net/zudajun/blog/670373

相关文章
|
3月前
|
人工智能 自然语言处理 数据可视化
2026企业智能客服选型指南:场景匹配、数据准备与组织协同
智能客服选型最大陷阱是未厘清自身需求就盲目启动。企业须先诊断服务模式(售前/售后/混合型),再以场景特征而非规模匹配产品;用历史数据验证标准化程度;明确AI定位为“拦截标准咨询,释放人力处理复杂问题”。知识库建设占项目60%–70%,需清洗对话、构建FAQ、配置多轮流程,并建立持续运营机制。技术是基础,运营定ROI。
|
存储 缓存 弹性计算
2024年阿里云最便宜云服务器出炉:61元、165元、99元、199元
2024年截止目前阿里云最便宜的云服务器已经出炉,轻量应用服务器2核2G3M带宽61元1年、2核4G4M带宽165元1年;云服务器经济型e实例2核2G3M带宽99元1年;云服务器通用算力型u1实例2核4G5M带宽199元1年。除此之外,还有幻兽帕鲁Palworld专用服务器4核16G10M带宽只要26.52元/1个月、79.56元/3个月、149.00元/6个月,8核32G10M带宽只要90.60元/1个月、271.80元/3个月。本文为大家分享2024年阿里云最便宜的各个云服务器。
12388 4
2024年阿里云最便宜云服务器出炉:61元、165元、99元、199元
|
3月前
|
Java API Maven
Spring Boot 创建项目详细介绍
如何创建一个 Spring Boot 项目,以及自动生成的目录文件作用。
291 2
|
前端开发 Java 数据库连接
Spring Boot 3 整合 Mybatis-Plus 动态数据源实现多数据源切换
Spring Boot 3 整合 Mybatis-Plus 动态数据源实现多数据源切换
|
3月前
|
前端开发 Java 数据库连接
Spring Boot 详细简介!
Spring Boot 是什么?能干啥?
352 0
Spring Boot 详细简介!
|
3月前
|
人工智能 JavaScript API
阿里云百炼CLI全解:命令行工具接入AI Agent实操与完整能力指南
在AI Agent快速迭代的开发环境中,开发者经常会遇到一个现实难题:不同AI智能体框架对接云端大模型、知识库、多模态生成工具时,需要反复编写接口代码,处理鉴权、请求封装、返回解析、异常重试等大量重复逻辑。每切换一套Agent框架,就要重新适配一整套API调用逻辑,不仅消耗大量开发时间,还容易出现鉴权不一致、参数不兼容、多工具能力无法复用等问题。百炼CLI作为官方开源的命令行工具,把平台上百款大模型、知识库检索、联网搜索、图像视频生成、语音处理等能力全部封装为终端可直接调用的指令,原生面向各类AI Agent做适配,支持脚本调用、CI流水线集成、本地Agent框架插件接入,大幅降低AI智能体的
387 1
|
3月前
|
数据采集 监控 供应链
1688 商品详情驱动的选品、竞品分析与采购实战指南
1688是“中国制造”的数字入口,汇聚60万源头工厂。本文详解如何通过API接口实现数据化选品:解析批发价阶梯、库存、供应商资质等核心字段;构建四层选品漏斗;以图搜款溯源跨境爆款;建立采购评分卡与动态监控模型,助力高效决策。(239字)
|
3月前
|
JSON fastjson Java
阿里巴巴为什么不建议 boolean 类型变量用 isXXX
为什么不推荐使用 isXXX 来命名呢?到底是用基本类型的数据好呢还是用包装类好呢?
168 3
阿里巴巴为什么不建议 boolean 类型变量用 isXXX
|
3月前
|
弹性计算 人工智能 编解码
阿里云服务器经济型、通用算力型、计算型、通用型、内存型实例区别及选择参考
本文解析了阿里云ECS五大主流实例规格的核心差异与选型策略。经济型e实例主打极致性价比,适合低负载场景,当前低至3.9折;通用算力型u2i兼顾性能与成本,提供1:1至1:8灵活配比,可享3折优惠;通用型g9i/g9a以1:4均衡配比适配多数企业应用,6.4折起;计算型c9i专为CPU密集型任务优化,支持高睿频处理器;内存型r9i则以1:8大配比满足海量数据驻留需求。文章结合各类型适用场景、最新活动政策及实操建议,帮助用户根据业务特征精准选型,并提醒先领优惠券享受折上折,实现算力预算最大化利用。
|
3月前
|
XML Java 数据格式
Spring中引入增强(IntroductionAdvice)的底层实现原理
一个 Java 类,没有实现A接口,在不修改Java类的情况下,使其具备A接口的功能。
106 1

热门文章

最新文章