MyBatis源码解析之Mapper接口的注册过程

MyBatis源码解析之Mapper接口的注册过程在此声明,此文章是对江荣波老师的《MyBatis3源码深度解析》的总结,尊重原作者。我们先来看一串代码。 @Test public void testDynamicSql() throws IOException { // 获取配置文件输入流 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
摘要由CSDN通过智能技术生成

MyBatis源码解析之Mapper接口的注册过程

在此声明,此文章是对江荣波老师的《MyBatis3源码深度解析》的总结,尊重原作者。

分析过程

我们先来看一串代码。

  @Test
  public void testDynamicSql() throws IOException {
   
        // 获取配置文件输入流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 通过SqlSessionFactoryBuilder的build()方法创建SqlSessionFactory实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 调用openSession()方法创建SqlSession实例
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取UserMapper代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        UserEntity entity = new UserEntity();
        entity.setPhone("18700001111");
        List<UserEntity> userList =  userMapper.getUserByEntity(entity);
        System.out.println(JSON.toJSONString(userList));   

    }

我们可以看到,要查询userList,我们得先调用SqlSession的getMapper()方法获取到UserMapper,但是UserMapper只是一个接口,所以getMapper()方法获取到的实例到底是什么呢?我们通过debug可以看到获取到的是一个动态代理对象MapperProxy。

下面是相关源代码

public class MapperProxy<T> implements InvocationHandler, Serializable {
   

  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
   
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @Override
  public Object invoke
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值