7. 分页插件

对于分页功能,MyBatisPlus 提供了分页插件,只需要进行简单的配置即可实现:

@Configuration
public class MybatisPlusConfig {
    // 旧版
//  @Bean
//   public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
//        // paginationInterceptor.setOverflow(false);
//        // 设置最大单页限制数量,默认 500 条,-1 不受限制
//        // paginationInterceptor.setLimit(500);
//        // 开启 count 的 join 优化,只针对部分 left join
//        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
//        return paginationInterceptor;
    //    }
    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

接下来就可以使用分页插件提供的功能了:

@Test
void hh(){
    Page<Employee> page = employeeService.page(new Page<>(1,2), null);
    List<Employee> employeeList = page.getRecords();
    employeeList.forEach(System.out::println);
    System.out.println("获取总条数:" + page.getTotal());
    System.out.println("获取当前页码:" + page.getCurrent());
    System.out.println("获取总页码:" + page.getPages());
    System.out.println("获取每页显示的数据条数:" + page.getSize());
    System.out.println("是否有上一页:" + page.hasPrevious());
    System.out.println("是否有下一页:" + page.hasNext());
}

其中的 Page 对象用于指定分页查询的规则,这里表示按每页两条数据进行分页,并查询第一页的内容,运行结果:
在这里插入图片描述

倘若在分页过程中需要限定一些条件,就需要构建 QueryWrapper 来实现:

@Test
void hh(){
   QueryWrapper<Employee> wrapper = new QueryWrapper<>();
   wrapper.lambda().between(Employee::getAge,20,50).eq(Employee::getGender, 1);
   Page<Employee> page = employeeService.page(new Page<>(1, 2), wrapper);
   List<Employee> employeeList = page.getRecords();
   employeeList.forEach(System.out::println);
}

此时分页的数据就应该是年龄在 20~50 岁之间,且 gender 值为 1 的员工信息,然后再对这些数据进行分页。

相关推荐

  1. MybatisPlus

    2024-01-13 12:22:03       12 阅读
  2. MybatisPlus的

    2024-01-13 12:22:03       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-13 12:22:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-13 12:22:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-13 12:22:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-13 12:22:03       20 阅读

热门阅读

  1. 正式阶段高等数学复习--导数的定义

    2024-01-13 12:22:03       35 阅读
  2. 《LIO-SAM阅读笔记》-为何要引入增量式里程计?

    2024-01-13 12:22:03       38 阅读
  3. Rust语言的Hello, World! 程序解析

    2024-01-13 12:22:03       25 阅读
  4. Prior information

    2024-01-13 12:22:03       31 阅读
  5. JWT相关问题及答案(2024)

    2024-01-13 12:22:03       29 阅读