1.环境介绍:
springboot2.7.4
pagehelper1.4.6
mybatis-plus3.5.1
2.需求分析
通过前端传回的分页要求的参数<页码,页数据量>,返回结果
实现
{ "code": 0, "message": "操作成功", "data": { "total": 5, "items": [ { "id": 1, "title": "背景2", "content": "测试,测试2,测试3,测试4......", "coverImg": "https://www.bing.com", "state": "已发布", "categoryId": 2, "createUser": 3, "createTime": "2024-02-01T14:43:27", "updateTime": "2024-02-01T14:43:27" }, { 。。。}
3.具体实现步骤
- 构建controller类,接受参数
public Result<PageBean<Article>> list( Integer pageNum,Integer pageSize, @RequestParam(required = false) Integer categoryId, @RequestParam(required = false) String state )
可通过@RequestParam指定该参数是否必须
- impl中实现
@Override public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) { PageBean<Article> pb = new PageBean<>();//PageBean包含一个total,和一个泛型List PageHelper.startPage(pageNum,pageSize);//使用PageHelper实现分页 Map<String,Object> map = ThreadLocalUtil.get(); Integer userId = (Integer) map.get("id");//查询用户创建的文章时,从threadLocal中读取用户id List<Article> as = articleMapper.list(userId,categoryId,state); Page<Article> p = (Page<Article>)as;//将List强制转换为Page子类,以调用Page子类中方法 pb.setTotal(p.getTotal()); pb.setItems(p.getResult()); return pb; }
- mapper.xml实现
<select id="list" resultType="com.example.springdemo.pojo.Article"> 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>
存在问题:idea在xml中没有代码提示实体类的全路径,影响编码体验
标签:分页,sprinboot,查询,pb,state,PageBean,id,Integer,categoryId From: https://www.cnblogs.com/jiajianchengchu/p/18001303