记录java项目中实现分页功能

  介绍两种常用的分页方式,github的PageHelper和MyBatis-Plus自带的分页

  一、使用PageHelper分页

  1、引入依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>

  2、封装请求类

public class PageRequest<T> {

    private T data;
    private int pageNum;
    private int pageSize;

    ... ... //get set 方法
}

  3、代码示例

@RequestMapping("/find")
public PageInfo<User> findByWhere(@RequestBody PageRequest<User> request) {
  PageHelper.startPage(request.getPageNum(),request.getPageSize());
   List<User> list = userService.findByWhere(request.getData());
   PageInfo pageInfo = new PageInfo(list);
   return pageInfo;
}

  4、传参示例

{
    "data":{
        "name":"测试"
    },
    "pageNum":"1",
    "pageSize":"10"
}

  二、使用MyBatis-Plus自带分页

  1、引入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3.1</version>
</dependency>

  2、请求封装类

public class PageRequest<T> {

    private T data;
    private Page page;

    public PageRequest() {
    }

   ... ... //get set 方法
}

  3、创建分页插件Bean

@Configuration
public class PageConfig {

    public PageConfig() {
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

  4、代码示例

@RequestMapping("/find")
public IPage<User> findByWhere(@RequestBody PageRequest<User> request) {
  Page page = request.getPage();
   List<User> list = userService.findByWhere(request);
   page.setRecords(list);
   return page;
}

//注意:Mapper或Dao中参数要有IPage
List<User> findByWhere(IPage<?> page,@Param("user") User user);

  5、参数示例

{
    "data":{
        "name":"测试"
    },
    "page":{
        "size":10,
        "current":1
    }
}

 

posted @ 2022-07-16 17:38  雷雨客  阅读(1396)  评论(0编辑  收藏  举报