zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    公式编辑器mathtype中一些符号显示方框的解决方法
    I got my first job
    我的第二个面试通知
    清空visual studio2010的查找历史
    King Back
    IIS中“使用 XSL 样式表无法查看 XML 输入”问题的解决
    JDBC 各种连接方式[转载]
    力扣每日刷题(1)
    力扣每天刷题(3)
    力扣每天刷题(2)
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14276547.html
Copyright © 2011-2022 走看看