关于mybatis-plus:底层到底做了什么-mybatisplus的一次select调用过程

4次阅读

共计 1726 个字符,预计需要花费 5 分钟才能阅读完成。

应用 mybatis-plus 创立 db mapper,只须要写一个接口继承 BaseMapper,比方示例中的 EntityMapper。

@Mapper
@Repository
public interface EntityMapper extends BaseMapper<Entity> {}
 

本文将解释在底层一次 select 调用是怎么实现。次要包含以下几个局部:

  1. 外围类及包
  2. 容器初始化
  3. Mapper bean 初始化
  4. 代理办法调用

外围类及所在包

次要波及以下包和类。

<artifactId>mybatis-plus-annotation</artifactId>
MybatisSqlSessionFactoryBean
ServiceImpl

<artifactId>mybatis-spring</artifactId>
MapperFactoryBean

<artifactId>mybatis-plus-core</artifactId>
MybatisConfiguration
MybatisMapperRegistry
MybatisMapperProxyFactory
MybatisMapperProxy
MybatisMapperMethod

容器初始化

spring 递归初始化以下类,包含:

MybatisPlusAutoConfiguration
MybatisSqlSessionFactoryBean
MybatisConfiguration
MybatisMapperRegistry

这里不一一阐明各类的初始化过程,只拿出 MybatisMapperRegistry。该类用来理论存储 mapper 的实现

public class MybatisMapperRegistry extends MapperRegistry {
    private final Configuration config;
    private final Map<Class<?>, MybatisMapperProxyFactory<?>> knownMappers = new HashMap();}

mapper bean 的初始化

1、spring 调用 MapperFactoryBean 初始化申明的 mapper 接口的 bean。


public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {public T getObject() throws Exception {return this.getSqlSession().getMapper(this.mapperInterface);
    }
}

该办法会递归调用上文曾经初始化的 MybatisConfigurationMybatisMapperRegistry,最终应用 MybatisMapperProxyFactory 生成代理类。

  1. 生成代理类,并放入 MybatisMapperRegistry 容器中

public class MybatisMapperProxyFactory<T> {protected T newInstance(MybatisMapperProxy<T> mapperProxy) {return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
    }
}

select 调用

  1. 获取注入的代理类 bean
  2. 调用 select 办法
  3. 理论调用代理办法

     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{}
    
    // 省略
     return new MybatisMapperProxy.PlainMethodInvoker(new MybatisMapperMethod(this.mapperInterface, method, this.sqlSession.getConfiguration()));

    这里的 MybatisMapperMethod,蕴含理论的 select 办法

到此流程根本执行实现。

正文完
 0