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.具体实现步骤

  1. 构建controller类,接受参数
    public Result<PageBean<Article>> list(
                Integer pageNum,Integer pageSize,
                @RequestParam(required = false) Integer categoryId,
                @RequestParam(required = false) String state
        )

    可通过@RequestParam指定该参数是否必须

  2. 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;
        }
    复制代码
  3. 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中没有代码提示实体类的全路径,影响编码体验

posted @   m4st  阅读(211)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示