mybatis-plus分页查询拥有内置的page方法,前端页面向后台传入page和limit,后台调用page()方法可以得到分页结果。
在Controller中添加分页方法
@ApiOperation(value = "分页讲师列表")
@GetMapping("{page}/{limit}")
public R pageList(
@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true)
@PathVariable Long limit){
Page pageParam = new Page<>(page, limit);
teacherService.page(pageParam, null);
List records = pageParam.getRecords();
long total = pageParam.getTotal();
return R.ok().data("total", total).data("rows", records);
}
package com.guli.edu.query;
@ApiModel(value = "Teacher查询对象", description = "讲师查询对象封装")
@Data
public class TeacherQuery implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "教师名称,模糊查询")
private String name;
@ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
private Integer level;
@ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
private String begin;//注意,这里使用的是String类型,前端传过来的数据无需进行类型转换
@ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
private String end;
}
将前端查询条件封装成查询条件对象。
service层接口声明方法
package com.guli.edu.service;
public interface TeacherService extends IService {
void pageQuery(Page pageParam, TeacherQuery teacherQuery);
}
service层实现类实现方法:
package com.guli.edu.service.impl;
@Service
public class TeacherServiceImpl extends ServiceImpl implements TeacherService {
@Override
public void pageQuery(Page pageParam, TeacherQuery teacherQuery) {
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.orderByAsc("sort");
if (teacherQuery == null){
baseMapper.selectPage(pageParam, queryWrapper);
return;
}
String name = teacherQuery.getName();
Integer level = teacherQuery.getLevel();
String begin = teacherQuery.getBegin();
String end = teacherQuery.getEnd();
if (!StringUtils.isEmpty(name)) {
queryWrapper.like("name", name);
}
if (!StringUtils.isEmpty(level) ) {
queryWrapper.eq("level", level);
}
if (!StringUtils.isEmpty(begin)) {
queryWrapper.ge("gmt_create", begin);
}
if (!StringUtils.isEmpty(end)) {
queryWrapper.le("gmt_create", end);
}
baseMapper.selectPage(pageParam, queryWrapper);
}
}
在Controller层中增加pageQuery()方法
@ApiOperation(value = "分页讲师列表")
@GetMapping("{page}/{limit}")
public R pageQuery(
@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable Long page,
@ApiParam(name = "limit", value = "每页记录数", required = true)
@PathVariable Long limit,
@ApiParam(name = "teacherQuery", value = "查询对象", required = false)
TeacherQuery teacherQuery){
Page pageParam = new Page<>(page, limit);
teacherService.pageQuery(pageParam, teacherQuery);
List records = pageParam.getRecords();
long total = pageParam.getTotal();
return R.ok().data("total", total).data("rows", records);
}
mybatis-plus自带的分页功能十分方便,平时我们编写前端时,分页是经常用到的,善于调用mybatis-plus自带的分页和条件查询能够提高我们的编程效率。希望这篇文章能对你有帮助,感谢你的阅读。我是黑马Jack,一起学习一起进步!