将链接添加到投影的嵌套对象中

nKo*_*ito 8 java spring spring-data spring-data-rest

我使用Spring Data REST的投影功能,以便在JSON中包含一些嵌套类型的对象:

{
   "id": 1,
   "name": "TEST",
   "user": {
      "id": 1,
      "name": "user1"
   },
   _links: {
       self: {
           href: "http://localhost:8082/accounts/1{?projection}",
           templated: true
       },
       user: {
           href: "http://localhost:8082/accounts/1/users"
       },
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在嵌套对象中生成链接?我想要以下JSON表示:

{
       "id": 1,
       "name": "TEST",
       "user": {
          "id": 1,
          "name": "user1",
          _links: {
              self: {
                  href: "http://localhost:8082/users/1",
                  templated: true
              },
           }
       },
       _links: {
           self: {
               href: "http://localhost:8082/accounts/1{?projection}",
               templated: true
           },
           user: {
               href: "http://localhost:8082/accounts/1/users"
           },
        }
    }
Run Code Online (Sandbox Code Playgroud)

PS我看到了这个问题,但我不知道如何在我的情况下使用它(如果它可能的话)

Joh*_*lph 5

我偶然发现了这个问题,正在寻找解决方案。在对摘录中的 Spring Data REST 文档部分进行一些摆弄之后,我发现了如何实现这一点。

我假设Account是您的根对象,并且您希望它有一个嵌套集合Users,其中每个用户依次拥有_links.

1:Excerpt为 Users 对象添加一个(无论如何,这是一种隐藏列表集合上不重要细节的方便技术)

@Projection(name = "userExcerpt", types = { User.class })
public interface UserExcerpt {
    String getName(); 
    String getEmail(); 
    ...
}
Run Code Online (Sandbox Code Playgroud)

2:Excerpt与您的UserRepository

@RepositoryRestResource(excerptProjection = UserExcerpt.class)
public abstract interface UserRepository extends JpaRepository<User, Long> ...
Run Code Online (Sandbox Code Playgroud)

3:添加一个Projectionfor Account

@Projection(types = {Account.class})
public interface AccountUsersProjection {

    String getName();
    ...
    Set<UserExcerpt> getUsers();
}
Run Code Online (Sandbox Code Playgroud)

这里重要的一点是您的 Projection 需要引用UserExcerpt而不是User. 这样返回的结果GET /accounts/projection=accountUsersProjection将如下所示:

{
  "_embedded" : {
    "accounts" : [ {
      "name" : "ProjA",
      "users" : [ {
        "name" : "Customer Admin",
        "email" : "customer@meshcloud.io",
        "_links" : {
          "self" : {
            "href" : "http://localhost:8080/users/2{?projection}",
            "templated" : true
          }, ...
        }
      } ], 
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/accounts/1"
        },
        ...
      }
    }  ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/accounts"
    },
    ...
  },
  "page" : {
    "size" : 50,
    "totalElements" : 2,
    "totalPages" : 1,
    "number" : 0
  }
}
Run Code Online (Sandbox Code Playgroud)