gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:31 25 4
gpt4 key购买 nike

我使用 Spring Data REST 的 projections功能以便在 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"
},
}
}

如何在嵌套对象中生成链接?我想要以下 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"
},
}
}

附言我看到了this question ,但不知道如何在我的案例中使用它(如果可能的话)

最佳答案

我偶然发现了这个问题,正在寻找解决方案。在摆弄 Spring Data REST docs section on Excerpts 之后我已经找到了如何实现这一目标。

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

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

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

2:Excerpt 与您的 UserRepository

相关联
@RepositoryRestResource(excerptProjection = UserExcerpt.class)
public abstract interface UserRepository extends JpaRepository<User, Long> ...

3:Account添加一个Projection:

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

String getName();
...
Set<UserExcerpt> getUsers();
}

此处重要的一点是您的投影需要引用 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
}
}

关于java - 将链接添加到投影的嵌套对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30327429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com