两步实现Mybatis-puls分页功能

Mybatis-plus实现分页步骤

1. 编写配置类,创建分页拦截器

@Configuration
@EnableTransactionManagement
@MapperScan("com.ao.takeaway.admin.dao")
public class MybatisConfig {
    /**
     * 分页拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

这里注意,如果你的mybatis-plus版本比较低,使用如下配置,在高版本的SpringBoot中, 会提示这种写法已过时。

@Configuration
@EnableTransactionManagement
public class MybatisConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

}

2. 分页查询数据

  1. 直接调用mybatis-plus中service层提供的page方法,传入相应的分页参数实现分页。
     @Override
     public Page<CategoryVo> listPage(PageParamsVo pageParamsVo) {
         Page<CategoryEntity> page = this.page(
                 new Page<CategoryEntity>(pageParamsVo.getCurrent(), pageParamsVo.getSize()),
                 new LambdaQueryWrapper<CategoryEntity>()
         );
     }
    
    • new Page<CategoryEntity>(pageParamsVo.getCurrent(), pageParamsVo.getSize()),传入对应的分页参数:当前页码, 每页显示的条数;
    • 如果需要带条件的查询语句,直接在new LambdaQueryWrapper<CategoryEntity>()加上查询条件即可。
  2. 也可以调用mapper层提供的selectPage方法,参数同上,都是一样的。
    public Page<CategoryVo> listPage(PageParamsVo pageParamsVo) {
    	Page<CategoryEntity> categoryEntityPage = this.baseMapper.selectPage(
    	      new Page<CategoryEntity>(pageParamsVo.getCurrent(), pageParamsVo.getSize()),
    	      new LambdaQueryWrapper<CategoryEntity>()
    	);
    }
    

3. 测试一下

@Test
public void list() {
    PageParamsVo pageParam = new PageParamsVo();
    // 当前页码
    pageParam.setCurrent(1L);
    // 每页显示的总条数
    pageParam.setSize(2L);
    Page<CategoryVo> page = categoryService.listPage(pageParam);
    // 查询到的数据列表
    List<CategoryVo> categoryList = page.getRecords();
    System.out.println(categoryList);
    System.out.println("共" + categoryList.size() + "条数据");
}

在这里插入图片描述

除了查询的数据,其他的分页参数信息也可以直接从Page对象中获取。
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值