spring boot api 分页查询

文章的思路来自于  https://blog.csdn.net/airjordon/article/details/72551786  在此感谢作者呼拉拉呼拉 。

先看代码 完了后再解释:

   第一:pom.xml 文件里 我的注入是 

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

第二:Conterllor 层里写入

@GetMapping("/pageable")
public Page<User> getEntryByPageable(@PageableDefault(value = 5, sort = { "id" }, direction = Sort.Direction.DESC)
                                             Pageable pageable) {
    return userService.findAll(pageable);

}

//page,第几页,从0开始,默认为第0页

//size,每一页的大小,默认为20

//sort,排序相关的信息

第三: repository层里面

                            Page<User> findAll(Pageable pageable);

第四:  在 service 接口

                           Page<User> findAll(Pageable pageable);

第五:  在 service  中的 imp类里面添加

  //具体参数根据个人设置                                 

@Override
public Page<User> findAll(Pageable pageable) {
    return userRepository.findAll(pageable);
}

第六 启动项目 

第七   http://localhost:8080/api/pageable  

相关的截图:

 

最后的图是启动项目的图。

 结果:{
    "content": [
        {
            "id": 23,
            "name": "MJF",
            "age": 10
        },
        {
            "id": 22,
            "name": "pMD",
            "age": 89
        },
        {
            "id": 21,
            "name": "test",
            "age": 11
        },
        {
            "id": 20,
            "name": "demo",
            "age": 22
        },
        {
            "id": 19,
            "name": "test",
            "age": 11
        }
    ],
    "pageable": {
        "sort": {
            "sorted": true,
            "unsorted": false
        },
        "offset": 0,
        "pageSize": 5,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "last": false,
    "totalElements": 23,
    "totalPages": 5,
    "number": 0,
    "size": 5,
    "sort": {
        "sorted": true,
        "unsorted": false
    },
    "numberOfElements": 5,
    "first": true
}

以id倒序排列的10条数据

当前页不是最后一页,

后面还有数据 总共有9页

每页大小为15 当前页为第0页

当前页是第一页

当前页是以id倒序排列的

当前页一共有15条数据

猜你喜欢

转载自blog.csdn.net/qq_40979622/article/details/82837638