Mybatis学习系列(六):获取对应的Mapper

本文是Mybatis学习系列的第六篇,主要探讨如何通过SqlSession获取Mapper并利用Mapper执行方法来获取数据。文章指出,实际操作中获取的是Mapper的代理对象,其具体执行逻辑将在下一篇文章中详细解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第五篇文章中,我们获取到了SqlSession对象,然后我们在执行的时候是通过获取Mapper,然后通过执行mapper的方法来获取我们需要的数据,这篇我们就看一下这个通过SqlSession获取Mapper的过程。

  DefaultSqlSession
  public <T> T getMapper(Class<T> type) {
    //这里调用的是configuration的getMapper方法
    return configuration.<T>getMapper(type, this);
  }

configuration
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //这里其实调用得失mapperRegistry的getMapper方法
    return mapperRegistry.getMapper(type, sqlSession);
  }

mapperRegistry
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    //首先我们在缓存中拿到当前class对应的MapperProxyFactory
    //MapperProxyFactory是在我们最开始解析Mapper的时候存入的
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    //这里必须是解析过的Mapper才能执行
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      //这里获取mapper对象,主要是通过mapperProxyFactory对象,传入我们的sqlSession对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

mapperProxyFactory
public T newInstance(SqlSession sqlSession) {
    //生成MapperProxy对象
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

protected T newInstance(MapperProxy<T> mapperProxy) {
    //这里其实是生成了一个当前mapper的代理对象
    //后续执行调用的时候其实是交给mapperProxy的
    //mapperProxy实现了InvocationHandler
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

这里我们就获取到了当前mapper的一个代理对象,这里交给MapperProxy去处理,我们在下一篇详细看一下这个执行的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值