【发布时间】: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