当我对商品进行分页查询的时候,由于错误的将分页插件位置放在了要进行分页查询数据的前几行,并没有紧挨着,导致分页查询失效。
下面是错误的代码:
@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);
这样才会实现分页效果,否则就会失去分页效果,返回全部数据