Mybatis |
您所在的位置:网站首页 › mybatisplus的selectPage方法 › Mybatis |
抛出疑问 Mybatis-plus的确能让我们写少很多重复代码,非常好用。那么其中最方便的就是Mapper接口继承BaseMapper就能获得增删改查的这个功能。那么这个功能的底层代码,究竟是怎么实现的呢? 原生Mybatis配置的原理毕竟Mybatis-plus是Mybatis的加强,所以Mybatis-plus肯定是基于Mybatis原来的机制来扩展的,沿着这个思路,我们先搞清楚一个问题,就是原生的mapper.xml文件最后是怎么跟对应的Mapper接口产生联系的。 既然是配置,那么在Mybatis里肯定有对应的配置类,这个类就是MappedStatement。最终在Configuration类中把MappedStatement对象添加进mappedStatements集合中进行管理。源码如下: public class Configuration { protected final Map mappedStatements = new StrictMap("Mapped Statements collection"); public void addMappedStatement(MappedStatement ms) { mappedStatements.put(ms.getId(), ms); } }假如有个mapper.xml文件定义如下: select * from user我们用debug模式来验证一下: 首先找到MybatisPlusAutoConfiguration配置类,会创建MybatisSqlSessionFactoryBean。 并设置MybatisConfiguration作为配置类。 这个MybatisConfiguration是很重要的类,里面会初始化一个mybatisMapperRegistry,后面有用。 public class MybatisConfiguration extends Configuration { /** * Mapper 注册 */ protected final MybatisMapperRegistry mybatisMapperRegistry = new MybatisMapperRegistry(this); }当创建MybatisSqlSessionFactoryBean时,会调用afterPropertiesSet()方法创建sqlSessionFactory。 @Override public void afterPropertiesSet() throws Exception { notNull(dataSource, "Property 'dataSource' is required"); state((configuration == null && configLocation == null) || !(configuration != null && configLocation != null), "Property 'configuration' and 'configLocation' can not specified with together"); this.sqlSessionFactory = buildSqlSessionFactory(); }然后buildSqlSessionFactory()方法的主要内容是解析mapper的xml文件。 然后继续深入,看bindMapperForNamespace()方法。 关键就在这个SQL注入器里。 利用模板模式,子类只需要重写injectMappedStatement()方法,上面初始化的部分都可以共用。AbstractMethod的子类有很多,我们选个有代表性的看一下,就可以推断其他的用途,比如Insert类。 由此可看出,BaseMapper里的语句信息模板,来自于枚举SqlMethod。 最终就是转成MappedStatement对象,然后添加注册,于是乎就有了这些CRUD操作的方法。 总结一下加载BaseMapper的过程: 初始化MybatisConfiguration和mybatisMapperRegistry。解析Mapper类,获取AbstractMethod集合。遍历AbstractMethod集合,然后调用各自实现的injectMappedStatement()方法,注入SQL。添加注册MappedStatement对象。非常感谢你的阅读,希望这篇文章能给到你帮助和启发。 觉得有用就点个赞吧,你的点赞是我创作的最大动力~ 我是一个努力让大家记住的程序员。我们下期再见!!! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |