【问题标题】:Pagination in Spring Data Rest for nested resourcesSpring Data Rest中嵌套资源的分页
【发布时间】:2014-10-19 15:11:53
【问题描述】:

当访问下面的 URL 时,我得到分页响应

/api/userPosts/

{
  "_links" : {
    "self" : {
      "href" : "/api/userPosts{?page,size,sort}",
      "templated" : true
    },
    "next" : {
      "href" : api/userPosts?page=1&size=20{&sort}",
      "templated" : true
    }
  },
  "_embedded" : {
    "userPosts" : [ {
     ...

但是,当访问以下 URL 时,Spring Data REST 没有开箱即用的分页 -

/api/users/4/userPosts

{
  "_embedded" : {
    "userPosts" : [ {

UserRepository 和 UserPostRepository 都是带分页的 JPARepository。结果,第二个 URL 抛出 GC Overhead exceeded 错误,因为返回的结果的行数很大。

@RepositoryRestResource(excerptProjection = UserProjection.class)
public interface UserRepository extends BaseRepository<User, Integer>, UserRepositoryCustom {

}

public interface UserPostRepository extends BaseRepository<UserPost, Long> {

}


@NoRepositoryBean
public interface BaseRepository<T, N extends Serializable> extends JpaRepository<T, N>, QueryDslPredicateExecutor<T> {

}

还有什么方法可以使用第二个 URL 进行分页?

【问题讨论】:

标签: java spring spring-data spring-data-rest


【解决方案1】:

简短而痛苦的回答:不。绝对不是。

长更痛苦的回答:是的。通过重写大部分 Spring Data、JPA 和 Hibernate。 问题的核心是,当您请求嵌套实体(集合与否)时,嵌套实体不是来自存储库的查询。但是是从实体返回的。 Spring Data / JPA 中没有用于分页的机制

Spring REST 中的 /api/users/4/userPosts 请求基本上是这样的:

User user = userRepository.findOne(4);
return user.userPosts;

所以检索 user.userPosts 是对嵌套实体的 Eager 或 Lazy 引用,并且无法对其进行分页。

实现这一目标的最简单也是唯一的解决方案是: 1.创建Spring Data搜索查询:UserPostRepository.findByUserId(Long id, Pagination pa) 2.创建自定义Spring MVC控制器进行映射

   @Get("/api/users/{id}/userPosts")
   public Page<UserPost> getUserPostsByUserId(Long id, Pagination pagi) {
     return userPostRepository.findByUserId(id, pagi);
  1. 重要!你不能!将 user.userPosts 注释为嵌套在 User 实体中,否则请求映射将发生冲突。
  2. 如果您想要用户实体 JSON 中此路径的导航超链接,那么您需要 用户实体 JSON 创建的自定义处理。它的文档记录很差,并且没有任何示例涵盖您需要探索一下的确切用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    相关资源
    最近更新 更多