pageHelper使用教程
1.引入分页插件(官方网站有两种方法引入插件,此例子为maven方式)
1.1 引入jar包
你可以从下面的地址中下载最新版本的 jar包:
https://oss.sonatype.org/content/repositories/releases/com/github/pagehelper/pagehelpe/
http://repo1.maven.org/maven2/com/github/pagehelper/pagehelper/
由于使用了sql 解析工具,你还需要下载 jsqlparser.jar:
http://repo1.maven.org/maven2/com/github/jsqlparser/jsqlparser/0.9.5/
1.2 maven方式引入
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>最新版本</version>
</dependency>
从maven仓库搜索最新版本
2.在application.yml中配置
#pagehelper分页插件
pagehelper:
helper-dialect: mysql
reasonable: false
support-methods-arguments: true
params: count=countsql
3.代码示例
3.1 mapper.xml文件
select * from user limit 0,10
select * from user
3.2 dao层代码(不需要改变)
List<TeacherStudent> queryStudentInfoByCourseId(Map<String,Object> map);
3.3 service层代码(pageNum,pageSize)
PageBean<TeacherStudent> queryStudentInfoByCourseId(Integer courseId, Integer pageNum, Integer pageSize);
3.4 Impl实现层代码
@Override
public PageBean<TeacherStudent> queryStudentInfoByCourseId(Integer courseId, Integer pageNum, Integer pageSize) {
if (pageNum==null || pageSize==null){
pageNum = 1;
pageSize = 10;
}
PageBean pageBean = new PageBean();
pageBean.setPageNum(pageNum);
pageBean.setPageSize(pageSize);
PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
Map<String,Object> map = new HashMap<>();
map.put("courseId",courseId);
map.put("pageNum",pageNum);
map.put("pageSize",pageSize);
List<TeacherStudent> teacherStudentList = teacherCourseDao.queryStudentInfoByCourseId(map);
int total = teacherStudentList.size();
if (null == teacherStudentList || total == 0) {
return new PageBean<>(500, "数据为空!");
}else {
return new PageBean<>(200,"Success",teacherStudentList);
}
}
3.5 controllrer层代码(前端传pageNum,pageSize)
@GetMapping("/queryStudentInfoByCourseId")
public PageBean<TeacherStudent> queryStudentInfoByCourseId(Integer courseId, Integer pageSize){
return teacherCourseService.queryStudentInfoByCourseId(courseId,pageNum,pageSize);
}
4.自定义封装PageBean
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class PageBean<T> implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private String msg;
private Integer pageNum = 0;
private Integer pageSize = 10;
private Integer total_pages;
private long records;
private List<T> data;
public PageBean(Integer code, List data) {
PageInfo<List> info = new PageInfo<>(data);
this.code = code;
this.records = info.getTotal();
this.total_pages = info.getPages();
this.pageNum = info.getPageNum();
this.pageSize = info.getPageSize();
this.data = data;
}
public PageBean(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public PageBean(Integer code, String msg, List data) {
PageInfo<List> info = new PageInfo<>(data);
this.code = code;
this.msg = msg;
this.records = info.getTotal();
this.total_pages = info.getPages();
this.pageNum = info.getPageNum();
this.pageSize = info.getPageSize();
this.data = data;
}
}
|