mybatis核心组件之MapperMethod


注释: 跟踪 mapper执行接口方法到数据库执行 sql语句的源码过程

// mybatis-spring
UserMapper mapper = context.getBean(UserMapper.class);
System.out.println(mapper.selectAny());

可以看到mapperMapperProxy产生的代理类,那么MapperProxy中可定有invok方法对目标方法进行了增强处理
在这里插入图片描述

MapperProxy

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 如果方法是Object类的方法,则直接反射执行
    if (Object.class.equals(method.getDeclaringClass())) {
        try {
            return method.invoke(this, args);
        } catch (Throwable var5) {
            throw ExceptionUtil.unwrapThrowable(var5);
        }
    } else {
       // 获取MapperMethod
        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        // 执行sql语句
        return mapperMethod.execute(this.sqlSession, args);
    }
}
  1. 先判断执行的方法是不是Object类的方法,比如tostringhashcode等方法,是的话则直接反射执行这些方法
  2. 如果不是,从缓存中获取MapperMethod,如果为空则创建并加入缓存,然后执行sql语句
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

构造函数

private final MapperMethod.SqlCommand command;
private final MapperMethod.MethodSignature method;

public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
    this.command = new MapperMethod.SqlCommand(config, mapperInterface, method);
    this.method = n
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值