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

@Mapper@Repositorypublic 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办法

到此流程根本执行实现。