• Mybatis源码:getMapper获取接口代理对象


    测试代码:

        @Test
        public void test01() throws IOException {
            //1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
            SqlSession session = sqlSessionFactory.openSession();
            try {
                EmployeeMapper employeeMapper= session.getMapper(EmployeeMapper.class);
                Employee emp = employeeMapper.getEmpById(1);
                System.out.println(emp);
    
                session.clearCache();
    
                Employee emp2 = employeeMapper.getEmpById(2);
                System.out.println(emp2);
                System.out.println(emp==emp2);
            } finally {
                session.close();
            }
        }
    
        private SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(inputStream);
        }
    

    在getMapper处打上断点,并进入方法,调用的是DefualtSqlSession的getMapper方法,最终调用的是Configuration的getMapper方法

    image-20210114112438460

    configuration调用的是mapperRegistry的getMapper方法

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
      return mapperRegistry.getMapper(type, sqlSession);
    }
    

    image-20210114112701531

    mapperRegistry的getMapper方法,先去获取mapperProxyFactory(mapper代理类的创建工厂),然后通过mapperProxyFactory的newInstance方法创建出对应的代理对象,点击进入

    image-20210114121745624

    发现MapperProxyFactory通过jdk动态代理创建了mapper接口的代理类MapperProxy。

    而MapperProxy实现了InvocationHandler接口

    image-20210114122134087

    所以最终getMapper返回的是一个代理对象

    image-20210114122344249

  • 相关阅读:
    1. Deep Q-Learning
    Ⅶ. Policy Gradient Methods
    Ⅴ. Temporal-Difference Learning
    idea在service窗口中显示多个服务
    pycharm下运行flask框架的脚本时报错
    windows下部署 flask (win10+flask+nginx)
    pip install selenium报错解决方法
    pip 及 selenium安装命令
    动作捕捉系统用于模仿学习
    柔性微创手术机器人性能实验验证
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14276547.html
Copyright © 2020-2023  润新知