使用PageHelper分页查询插件时遇到的坑

当我对商品进行分页查询的时候,由于错误的将分页插件位置放在了要进行分页查询数据的前几行,并没有紧挨着,导致分页查询失效。
下面是错误的代码:

@Override
    public PageVO selectListByUserId(Integer currentPage, Integer pageSize, String userId) {
        PageHelper.startPage(currentPage, pageSize);
        // 查询用户信息
        User user = userMapper.selectById(userId);
        // 根据 userId 进行条件查询
        LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductInfo::getUserId, userId)
                .orderByDesc(ProductInfo::getCreateTime);
        List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);
}

PageHelper插件是对查询出来的数据进行二次处理,然后实现分页的。如果是正常的CURD,那么这句代码

LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ProductInfo::getUserId, userId).orderByDesc(ProductInfo::getCreateTime);
List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);

查询到的数据应该是所有数据(我的数据库此时只有20条数据)。

当我改正代码以后:
 

    @Override
    public PageVO selectListByUserId(Integer currentPage, Integer pageSize, String userId) {
        // 启动分页
        PageHelper.startPage(currentPage, pageSize);

        // 根据 userId 进行条件查询
        LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductInfo::getUserId, userId)
                .orderByDesc(ProductInfo::getCreateTime);
        List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);

        // 查询用户信息(只需查询一次)
        User user = userMapper.selectById(userId);

        // 将商品信息转换为 ProductInfoVO 对象
        List<ProductInfoVO> productInfoVOList = new ArrayList<>();
        for (ProductInfo productInfo : productInfos) {
            ProductInfoVO productInfoVO = new ProductInfoVO();
            // 将商品信息拷贝进VO对象
            BeanUtil.copyProperties(productInfo, productInfoVO);
            // 填充用户信息到VO对象
            productInfoVO.setAvatar(user.getAvatar());
            productInfoVO.setNickName(user.getNickName());
            productInfoVOList.add(productInfoVO);
        }

        // 使用 PageHelper 获取分页元数据
        PageInfo<ProductInfo> pageInfo = new PageInfo<>(productInfos);

        // 构建 PageVO 对象并返回
        PageVO pageVO = new PageVO();
        pageVO.setTotal(pageInfo.getTotal()); // 总记录数
        pageVO.setRecords(productInfoVOList); // 当前页数据
        return pageVO;
    }
}

这里面要把 :

// 启动分页
PageHelper.startPage(currentPage, pageSize);

紧邻着放在:

// 根据 userId 进行条件查询
LambdaQueryWrapper<ProductInfo> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ProductInfo::getUserId, userId)
        .orderByDesc(ProductInfo::getCreateTime);
List<ProductInfo> productInfos = productInfoMapper.selectList(queryWrapper);

 这样才会实现分页效果,否则就会失去分页效果,返回全部数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值