我有一个具有某些属性的实体 A,并引用了另一个实体 B
A{
....
@ManyToOne(fetch=FetchType.LAZY)
B b;
...
}
B 相同(@onetomany 用于 B 中的 A)。它是双向关系。 在为实体 A 调用 Web 服务时,它会在响应 json 中提供指向 B 实体的链接,而不是整个对象。 我想要 Web 服务响应 JSON 中的整个对象,而不是指向相关实体的链接。 我怎样才能做到这一点? 我正在使用 springboot + spring data jpa + hibernate 作为 jpa 提供程序 + spring 4
最佳答案
为了在输出 JSON 中嵌套相关对象,您必须使用 projections .
public class User {
private String name;
private Address address;
}
public class Address {
private String street;
}
public interface UsersRepository extends JpaRepository<User, Long> {
// Custom methods
}
给你
{
"name": "John",
"_links": {
"self": "http://localhost:8080/users/1",
"address": "http://localhost:8080/addresses/1"
}
}
但是有投影:
@Projection(name = "inlineAddress", types = { User.class })
public interface UserInlineAddressProjection {
String getName();
Address getAddress();
}
@RepositoryRestResource(excerptProjection = UserInlineAddressProjection.class)
public interface UsersRepository extends JpaRepository<User, Long> {
// Custom methods
}
结果如下:
{
"name": "John",
"address": {
"street": "Stormtroopers str. 1"
},
"_links": {
"self": "http://localhost:8080/users/1",
"address": "http://localhost:8080/addresses/1"
}
}
这是实现它的唯一方法
关于json - 在 spring data rest 中序列化时获取惰性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118193/