在實際開發過程中,分頁顯示功能是非常常見的
這里使用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分頁條件查詢