1. 在 sql 中使用 limit 进行分页查询
用法:LIMIT [offset,] rows
1
| SELECT * FROM article LIMIT 10, 10
|
offset 是相对于首行的偏移量(首行是 0),rows 是返回条数
mapper 中可以传变量,即在实际使用的时候 offset 与 rows 可以用变量替代
2. 使用第三方库进行分页查询
编写PageBean
1 2 3 4 5 6 7 8 9
| @Data @AllArgsConstructor @NoArgsConstructor public class PageBean<T> { private Long total; private List<T> items; }
|
编写分页查询的路径
1 2 3 4 5 6 7 8 9
| @GetMapping public Result<PageBean<Article>> list(Integer pageNum,Integer pageSize, @RequestParam(required = false)String categoryId, @RequestParam(required = false)String state){ PageBean<Article> bean=articleService.list(pageNum,pageSize,categoryId,state); return Result.success(bean); }
|
处理数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Override public PageBean<Article> list(Integer pageNum, Integer pageSize, String categoryId, String state) { PageBean<Article> page = new PageBean<>(); PageHelper.startPage(pageNum,pageSize); Map<String,Object> map = ThreadLocalUtil.get(); Integer userId =(Integer) map.get("id"); List<Article> list = articleMapper.list(userId,categoryId,state); Page<Article> p = (Page<Article>) list; page.setTotal(p.getTotal()); page.setItems(p.getResult()); return page; }
|
mapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <select id="list" resultMap="All"> select * from article <where> <if test="categoryId!=null"> category_id =#{categoryId} </if> <if test="state!=null"> and state=#{state} </if> and create_user =#{userId} </where> </select>
|