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

  • 相关阅读:
    面试笔试题目集
    [vs2010]:fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "StdAfx.h"”?
    [数据库] SQLite常见问题解答
    安卓学习资料总结39
    Android 学习资料总结40
    python变量的定义和使用
    python运算符
    python的注释
    print输出函数
    python数据类型转换
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14276547.html
Copyright © 2011-2022 走看看