mybatisplus流程一
查询示例

从一个简单的查询开始分析mybatisplus运行流程
baseMapper
首先来看getBaseMapper方法


说明这里拿到的baseMapper其实就是TestTableDao
而TestTableDao只是一个interface,继承baseMapper,为什么可以通过@Autowired注入,baseMapper又是怎么执行selectById,他的方法实现在哪里?

通过debug可以看到,getBaseMapper拿到的是MybatisMapperProxy这个bean,他的mapperInterface是TestTableDao
那MybatisMapperProxy这个bean又是谁注入的?
MybatisPlusAutoConfiguration
pom中引入了mybatis-plus-boot-starter这个依赖,做了mybatis的自动装配
那MybatisMapperProxy肯定就是在这个过程中被注入
查看mybatis-plus-boot-starter.jar的spring.factories
根据名字,查看MybatisPlusAutoConfiguration

注入SqlSessionFactory
注入SqlSessionTemplate
import AutoConfiguredMapperScannerRegistrar
在AutoConfiguredMapperScannerRegistrar中,注册了MapperScannerConfigurer这个bean
需要注意的是:如果使用了@MapperScan,不会import AutoConfiguredMapperScannerRegistrar
MapperScan import了MapperScannerRegistrar

在MapperScannerRegistrar中也注入了MapperScannerConfigurer这个bean
MapperScannerConfigurer

MapperScannerConfigurer使用ClassPathMapperScanner扫描basePackage,basePackage即@MapperScan配置的basePackages,也就是dao所在目录
也就是说,上面用到的TestTableDao是在这个地方被注册


为所有dao设置beanClass为MapperFactoryBean

MapperFactoryBean的getObject又调用getSqlSession().getMapper(this.mapperInterface);获取bean
这里的getSqlSession()就是MybatisPlusAutoConfiguration中注册的SqlSessionTemplate
SqlSessionTemplate又调用getConfiguration().getMapper(type, this);


MapperFactoryBean.getObject最终拿到的是MybatisMapperProxy,符合上面debug的结果
总结:@MapperScan注解import了MapperScannerRegistrar,MapperScannerRegistrar注册MapperScannerConfigurer,MapperScannerConfigurer扫描注册@MapperScan.basePackages下的类,并注册为MapperFactoryBean,MapperFactoryBean的getObject方法最终返回MybatisMapperProxy
也就是testTableService.getBaseMapper().selectById(testTableEntity.getId());实际是MybatisMapperProxy.selectById
MybatisMapperProxy
继续来看MybatisMapperProxy是怎么执行的selectById


最终运行的是MybatisMapperMethod.execute

这里的sqlSession还是SqlSessionTemplate
又调用sqlSessionProxy

这里又去获取SqlSession,拿到的是DefaultSqlSession



中间是一些mybatis插件的执行过程,最终调用java.sql.Statement执行数据库查询
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)