【问题标题】:How can I include references in spring rest response?如何在春季休息响应中包含参考资料?
【发布时间】:2018-10-04 19:48:30
【问题描述】:

我已经用 spring 定义了两个 JPARepository:“Person”和“Address”。我还指定了 Person 和 Address 之间的关系。

我可以通过以下方式获取所有人: http://localhost:8080/person/

所有地址为:http://localhost:8080/address/

我还可以通过http://localhost:8080/person/1/address获得一个人的地址

现在我想在收到请求时将每个人的地址作为嵌套地址:http://localhost:8080/person/

如何在响应中包含关系?

@nicolasl 要求的我的课程

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    @OneToOne
    @JoinColumn(name = "address_id")
    private Address address;


    //Getter/Setter here


}

@Entity
public class Address {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable = false)
    private String location;

    @OneToOne(mappedBy = "address")
    private Person person;

    //Getter/Setter here
}

【问题讨论】:

标签: java spring spring-data-jpa spring-data


【解决方案1】:

好吧,我猜你不能,不使用 spring 提供的自动休息引擎。其余 API 将返回链接以检索 JSON 响应的“_links”部分中的相关实体(您可以在http://stateless.co/hal_specification.html 中阅读更多相关信息)。您必须调用这些链接来检索您的地址。

解决此问题的另一种方法是实现您自己的存储库并组装您自己的 JSON 响应。

【讨论】:

  • 在@nicolasl 原帖中完成
  • 更新了答案
  • 我不明白他们为什么不实施这个选项。以这种方式检索 10 个人(带有地址)将导致 11 个 http 请求和 11 个 db 请求。太慢了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
相关资源
最近更新 更多