通过mybatis-generator和pagehelper实现DAO层零代码
通过使用mybatis-generator自动生成mybatis相关代码我们可以自动生成DAO层代码,自动生成的查询代码并不支持分页操作。但在实际的应用中,分页查询几乎是必须的功能。那如何在不改动自动生成代码或添加新代码的前提下,完成分页功能呢?
答案是 pagehelper。
pagehelper是一个mybatis插件,提供了对分页查询的支持。
1. POM配置
<!-- mybatis 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!-- 我已经忘记为何要替换jsqlparser版本了,如果pagehelper-spring-boot-starter一切使用正常的话,下面这两个配置就不需要啦! -->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
<exclusions>
<exclusion>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.2</version>
</dependency>
2. PageHelper插件自动注册
pagehelper自动配置功能实现了pagehelper插件的自动注册,所以不需要在mybatis的配置文件中单独配置。
com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration
3. 实现分页的最佳实践
- UI端传递pageNum、pageSize到Controller层;
- Controller传递pageNum、pageSize到Service,Service层通过com.github.pagehelper.page.PageMethod#startPage(int, int)方法设置分页查询信息。pageNum、pageSize等信息保存到com.github.pagehelper.Page对象以ThreadLocal的形式传递给DAO。
- DAO执行查询,PageHelper插件重写sql查询(具体讲就是在查询语句最后添加limit语句)并执行count操作,最终返回com.github.pagehelper.Page对象;
- Controller层通过com.github.pagehelper.PageSerializable#of(List list)方法封装查询结果并返回给UI端。
最终通过mybatis-generator和pagehelper的完美结合,我们没有在DAO层写一句代码就可以完成增删改查操作以及对分页的支持,提升我们的开发效率。
当然,如果需要执行更加复杂的SQL语句,建议单独增加Mapper类和mapping文件进行处理,而不要改动自动生成的代码,以防被再次自动生成的代码覆盖掉。