Mapper方法调用过程

Mapper方法调用过程

Mapper方法调用时序

在这里插入图片描述

@Test
  public void testMybatis() throws IOException, SQLException {
   
    BaseDataTest.createBlogDataSource();
    InputStream inputStream = Resources.getResourceAsStream("MapperConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    CachedAuthorMapper cachedAuthorMapper = sqlSession.getMapper(CachedAuthorMapper.class);
    cachedAuthorMapper.selectAuthorWithInlineParams(1);
  }

使用Mybatis框架执行sql语句,在获取到sqlSession对象后,会调用getMapper方法根据自己定义的Mapper接口获取Mybatis为我们生成的动态代理对象,即MapperProxy。当我们调用Mapper接口的方法时,例如上面的selectAuthorWithInlineParams方法时会被MapperProxy拦截,进而执行invoke方法,在此方法中会调用MapperMethod的execute方法执行sql。在execute方法中,会调用SqlCommand对象的getType方法获取sql语句的类型,调用MethodSignature对象的resolveReturnType获取方法返回值类型,调用convertArgsToSqlCommandParam解析Mapper方法参数,最后根据sql语句类型调用SqlSession的对应方法执行sql语句。

MapperProxy拦截目标方法执行

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
    try {
   
      // 从Object类继承的方法不做处理
      if (Object.class.equals(method.getDeclaringClass())) {
   
        return method.invoke(this, args);
      } else if (method.isDefault()) {
   
        if (privateLookupInMethod == null) {
   
          return invokeDefaultMethodJava8(proxy, method, args);
        } else {
   
          return invokeDefaultMethodJava9(proxy, method, args);
        }
      }
    } catch (Throwable t) {
   
      throw ExceptionUtil.unwrapThrowable(t);
    }

    // 对Mapper接口中定义的方法进行封装,生成MapperMethod对象
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

MapperMethod的execute方法

public Object execute(SqlSession sqlSession, Object[] args) {
   
    Object result;
    // 获取sql语句的类型
    switch (command.getType()) {
   
      case INSERT: {
   
        // 获取参数信息
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值