【问题标题】:best way to save child resource Spring Data REST保存子资源 Spring Data REST 的最佳方法
【发布时间】:2016-09-01 10:22:56
【问题描述】:

我有两个实体:

@Entity
public class Father{
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  @OneToMany(mappedBy = "father",cascade = CascadeType.ALL, fetch =     FetchType.LAZY)
  private Set<Child> children;
  // other
}

@Entity
public class Child{
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  @ManyToOne(fetch = FetchType.EAGER)
  private Father father;
  // other
}

通过使用 Spring Data REST 我可以保存实体:

通过POST创建父亲

{
"name":"Father1"
}

然后通过 POST http://localhost:8080/children/ 创建子节点

{
"name":"Child1",
"father":"http://localhost:8080/fathers/1"
}

或者我可以保存两个独立的实体并将给定 URI 指向的资源绑定到资源。

哪种方式最好? 我无法理解这一点:我可以通过以下方式将孩子添加到父亲:

curl -X PUT -H "ContentType: text/uri-list" http://localhost:8080/children/1 http://localhost:8080/fathers/1/children 

【问题讨论】:

  • 由于关系映射在子节点中,我假设您只能通过设置父亲属性来设置它。也许使用 ManyToMany,这会有所不同,因为那时您可以先创建实体然后链接它们,而无需在此过程中更改它们中的任何一个。但老实说,这只是猜测,也必须解决这个问题,所以:好问题。
  • “哪种方式最好?” 衡量标准是什么? PUT 替换资源,因此要添加子项,列表不仅必须包含新的子项,还必须包含现有的子项。

标签: spring rest spring-data-rest spring-hateoas


【解决方案1】:

一开始你创建了父实体并保存了它。

然后您想将新孩子绑定到您的孩子,您将在您的孩子创建请求中进行以下操作

{
  "father.id": 1,
  "name":"SomeName"
}

Spring会在收到请求时自动转换为父实体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-15
    • 2019-09-30
    • 1970-01-01
    • 2018-04-25
    • 2011-12-13
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多