springboot实现分页查询
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中没有代码提示实体类的全路径,影响编码体验
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!