上一篇教程中我讲述了如何将Springboot和MyBatis结合操作数据库进行增删改查。其中查这一步仅仅只是将所有符合条件的数据用list返回,而在实际做项目的时候,这样肯定是不行的,将查找的数据分页是必不可少的,一般分页会由服务器端来完成。本篇我们就介绍一个简单的服务器端分页的方式,即用pagehelper这个分页插件来进行分页。
首先在build.gradle中的dependencies中添加pagehelper的依赖包
implementation 'com.github.pagehelper:pagehelper-spring-boot-starter:1.2.13'
注意要引入用于Springboot的pagehelper的包。
然后在application.properties中配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
具体这几个参数的含义可以查看官方文档
接着修改SubjectController中的查的方法findSubjects如下
@RequestMapping(value = "/subjects")
public ResponseData findSubjects(final String name, final Integer index, final Integer size){
Page<Subject> page = PageHelper.startPage(index + 1, size);
List<Subject> subjectList = subjectMapper.findSubjects(name);
ResponseData responseData = ResponseData.ok();
responseData.putDataValue("pageCount", page.getPages());
responseData.putDataValue("total", page.getTotal());
responseData.putDataValue("subjects", subjectList);
return responseData;
}
这里要注意的是index,就是页码要从1开始计算,而前端一般是从0开始,所以我这边加了1。
运行项目,为了测试,可以先在数据库中多添加几条数据,再在浏览器中输入http://localhost:8080/subject/subjects?name=&index=0&size=5,就可以看到每次查询到了5条数据。
分页查询结果
本篇教程中的代码还是参考我在github上面的代码https://github.com/ahuadoreen/studentmanager