在实际开发过程中,分页显示功能是非常常见的
这里使用Mybatis Plus进行分页查询
首先需要加入分页插件
MyBatisPlusConfig
import com.baomidou.mybatisplus.core.injector.ISqlInjector; import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration @MapperScan("com.atguigu.eduService.mapper") public class MyBatisPlusConfig { /** * SQL 执行性能分析插件 * 开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 */ @Bean @Profile({"dev","test"})// 设置 dev test 环境开启 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(1000);//ms,超过此处设置的ms则sql不执行 performanceInterceptor.setFormat(true); return performanceInterceptor; } /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
然后在Controller层编写
@ApiOperation(value = "分页讲师列表") @GetMapping("/pageList/{page}/{limit}") public Result pageList( @ApiParam(name = "page",value = "当前页码",required = true) @PathVariable Long page, @ApiParam(name = "limit",value = "每页记录数",required = true) @PathVariable Long limit){ Page<EduTeacher> pageParam = new Page<>(page,limit); eduTeacherService.page(pageParam,null); long total = pageParam.getTotal(); //总记录数 List<EduTeacher> list = pageParam.getRecords(); return Result.succ().data("total",total).data("list",list); }
这里,Result是自定义的统一返回结果集
import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.HashMap; import java.util.Map; @Data public class Result { @ApiModelProperty(value = "是否成功") private Boolean success; @ApiModelProperty(value = "返回码") private Integer code; @ApiModelProperty(value = "返回消息") private String message; @ApiModelProperty(value = "返回数据") private Map<String, Object> data = new HashMap<String, Object>(); private Result(){} public static Result succ(){ Result result = new Result(); result.setSuccess(true); result.setCode(ResultCode.SUCCESS); result.setMessage("成功"); return result; } public static Result error(){ Result result = new Result(); result.setSuccess(false); result.setCode(ResultCode.ERROR); result.setMessage("失败"); return result; } public Result success(Boolean success){ this.setSuccess(success); return this; } public Result message(String message){ this.setMessage(message); return this; } public Result code(Integer code){ this.setCode(code); return this; } public Result data(String key, Object value){ this.data.put(key, value); return this; } public Result data(Map<String, Object> map){ this.setData(map); return this; } }
如果感觉有帮助的小伙伴记得点个收藏加个关注哦~
下篇分享:mp分页条件查询