一、整体思路
- 前端传递两个参数:page(当前页码)、pageSize(每页数据条数)
- Service 层手动计算分页起始下标:start = (page -1)*pageSize
- Mapper 写两条 SQL:
- 一条统计符合条件数据总条数select count(*) from 表
- 一条使用 limit 截取当前页数据select * from 表 limit start,pageSize
- 自定义PageBean实体封装总条数 total、当前页数据 rows,统一返回前端
二、实现代码
1.新建分页封装类 PageBean
package com.example.myweb.pojo; import lombok.Data; import java.util.List; @Data public class PageBean { private Long total; //总商品条数 private List<Goods> rows; //当前页商品数据 }2.GoodsMapper新增两条分页 SQL
//1. 多条件统计商品总数量 @Select("<script>SELECT count(*) FROM goods <where>" + "<if test='name != \"\"'>name LIKE CONCAT('%',#{name},'%')</if>" + "<if test='category != \"\"'>category=#{category}</if></where></script>") Long countByCondition(@Param("name")String name,@Param("category")String category); //2. limit分页查询商品 @Select("<script>SELECT * FROM goods <where>" + "<if test='name != \"\"'>name LIKE CONCAT('%',#{name},'%')</if>" + "<if test='category != \"\"'>category=#{category}</if></where>" + "ORDER BY create_time DESC limit #{start},#{pageSize}</script>") List<Goods> selectPageData(@Param("start")Integer start, @Param("pageSize")Integer pageSize, @Param("name")String name, @Param("category")String category);3.GoodsServiceImpl 分页业务
@Override public PageBean goodsPage(Integer page,Integer pageSize,String name,String category){ //页码容错 int safePage = page==null||page<1 ? 1 : page; int safeSize = pageSize==null||pageSize<1 ? 10 : pageSize; //计算起始偏移量 int start = (safePage-1)*safeSize; //查询总条数 Long total = goodsMapper.countByCondition(name,category); //分页截取数据 List<Goods> list = goodsMapper.selectPageData(start,safeSize,name,category); return new PageBean(total,list); }4.GoodsController 接口
@GetMapping public Result<PageBean> goodsPage( @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(required = false) String name, @RequestParam(required = false) String category ){ PageBean pageBean = goodsService.goodsPage(page,pageSize,name,category); return Result.success(pageBean); }5.前端取值
axios.get("http://localhost:8080/goods?"+params).then(res=>{ if(res.data.code === 1){ this.goodsList = res.data.data.rows; this.totalCount = res.data.data.total; } })