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

概述

在页面功能中经常会使用到分页对象,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()));

    }
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值