使用mybatis-plus基于BaseMapper的Page对象按条件分页查询

tech2023-05-30  46

概述

在页面功能中经常会使用到分页对象,mybatis-plus中也为我们提供了分页操作对象Page

分页方法

需要注意的是Page对象接收当前页和当前页显示条数两个参数

//currentPage是页码,size条数 public PageResult<TbLabel> search(TbLabel tbLabel,int currentPage, int size){ if (currentPage==0||size==0){ currentPage=1; size=5; } //basePage自带分页 Page<TbLabel> page = new Page<>(currentPage,size); QueryWrapper<TbLabel> queryWrapper = new QueryWrapper<>(); //lambda表达式写法,推荐使用 //queryWrapper.lambda().eq(TbLabel::getLabelName,tbLabel.getLabelname()); queryWrapper.like("labelname",tbLabel.getLabelname()) .eq("state",tbLabel.getState()); IPage<TbLabel> tbLabelIPage = tbLabelDao.selectPage(page, queryWrapper); return new PageResult<TbLabel>(tbLabelIPage.getTotal(),tbLabelIPage.getRecords()); }

配置类

记得为分页对象配置PaginationInterceptor 对象,否则可能会导致total一些参数的不可用。

@Configuration public class MybatisplusConfig { @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); } }

这里的话,需要注意的是currentPage和size的数据类型选择问题,其实可以选int型或者是Integer型。

Integer是int的封装类,它的默认值是null,在进行数据校验的时候是双等于null来进行判断,而int则是双等于0进行判断,在处理的时候。在考虑逻辑的时候,如果数据类型为null,或者0,可以有两种选择,一种是返回一个提示给前端(error,xx值为空)或者是,对这些值进行初始化,返回给前端一些初始化的值。在选择的时候,一般倾向于选择后者,因为能给到用户体验较好一点。

下面给出了另一种方案,以供参考

//分页返回brand对象 @RequestMapping("/findBrandPage") public Result findBrandPage(@RequestBody TbBrand tbBrand, Integer currentPage, Integer size){ if (currentPage==null||size==null){ return new Result("0","error"); } QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>(); queryWrapper.select("first_char","COUNT(*)").groupBy("first_char").having("count(*)>{0}",2); IPage<TbBrand> iPage = iTbBrandService.page(new Page<>(currentPage,size),queryWrapper); return new Result("1","good",new PageResult(iPage.getTotal(),iPage.getRecords())); }
最新回复(0)