【发布时间】:2017-08-26 23:19:43
【问题描述】:
我对 Spring Boot / Spring Data 有疑问,我只能在一个方向上创建嵌套实体。
我有两个实体,Parent 和 Child,Parent 与 Child 实体具有 OnetoMany 关系。
如果我创建一个孩子,通过这样做:
POST http://localhost:8080/children
{
"name": "Tenzin"
}
然后通过执行以下操作创建父级:
POST http://localhost:8080/parents
{
"name": "Fred and Alma",
"children": [ "http://localhost:8080/children/1" ]
}
它不起作用。
但是,如果我先创建父级,然后通过这样做创建一个新子级,它确实有效:
POST http://localhost:8080/children
{
"name": "Jacob",
"parent": [ "http://localhost:8080/parents/1" ]
}
为什么会这样,这是预期的行为还是我做错了什么?
是因为 Parent 实体(见下文)在 children 属性上有 cascade=ALL 吗?
父实体:
@Entity
public class Parent {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy="parent", cascade = CascadeType.ALL)
private List<Child> children = new ArrayList<>();
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
子实体:
@Entity
public class Child {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
private Parent parent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
【问题讨论】:
-
你能展示你的回购吗?
-
嘿 Cepr0,它是:github.com/simbro/spring-boot-practice-application - 虽然我想我已经弄清楚了 - 见下文。
标签: spring-boot spring-data spring-data-rest