java - 为什么 Spring Data REST 搜索返回没有页面信息的页面?

标签 java spring spring-data-jpa

我正在使用Spring Data REST我正在尝试对查询进行分页,但没有得到我期望的所有信息。

我的存储库定义为

public interface UserRepository extends PagingAndSortingRepository<User, String>
{
    List<User> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

当我使用此 URL 查询时

http://localhost:43434/api/users/search/findByNameContainingIgnoreCase?name=mic

然后我得到以下信息。它是分页的,如果我添加 &page=2 然后它会遍历页面。但是,它不包含有关当前页面、总页数等信息。

{
  "_embedded" : {
    "users" : [ {
      "name" : "Michael",
      "_links" : {
        "self" : {
          "href" : "http://localhost:43434/api/users/1"
        }
    }, 
    ... more users
    ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:43434/api/users/search/findByNameContainingIgnoreCase?name=mic"
    }
  }
}

当我直接查看users时,即http://localhost:43434/api/users/,然后我得到一个方便的链接和页面部分(因为它是定义的)作为PagingAndSortingRepository):

{
  ... first page of users...

  "_links" : {
    "first" : {
      "href" : "http://localhost:43434/api/users?page=0&size=20"
    },
    "next" : {
      "href" : "http://localhost:43434/api/users?page=1&size=20"
    },
    "last" : {
      "href" : "http://localhost:43434/api/users?page=49&size=20"
    }
    ... other links
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1000,
    "totalPages" : 50,
    "number" : 0
  }
}

为什么我没有收到与主集合页面相同的搜索页面分页信息?它的实现方式不同吗?

最佳答案

啊,答案就在我面前in the documentation !

To use paging in your own query methods, you need to change the method signature to accept an additional Pageable parameter and return a Page rather than a List.

问题是我返回了一个List。这将默默地失败,因为它将显示分页数据,但不会显示有关页面的元数据。您必须返回一个 Page 才能公开页面元数据。

public interface UserRepository extends PagingAndSortingRepository<User, String>
{
    Page<User> findByNameContainingIgnoreCase(String name, Pageable pageable);
}

关于java - 为什么 Spring Data REST 搜索返回没有页面信息的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56810979/

相关文章:

java - 将 jPCT 与 Vuforia/QCAR SDK 集成

java - 在 $TOMCAT/conf/context.xml 上为 JNDI 设置资源

java - Spring Boot - 如何在开发过程中禁用@Cacheable?

hibernate - OpenSessionInView 过滤器导致 grails run-app 爆炸?

spring-data-jpa - 使用 Spring Data JPA 的 Kotlinic 模式 "query by example"

java - getResourceAsStream - 它被读取为什么编码?

java - 无法通过jar特定任务编写build.gradle

spring - 如何从 Spring Security 中排除 Controller ?

java - 具有单向关系的 Criteria API

java - 没有计数的具有规范的 spring-data 切片