我有一個Spring Boot/Spring Data的問題,我只能在一個方向上創建嵌套實體。Spring Data Rest - 只能在一個方向創建嵌套實體
我有兩個實體,父和子,父母與子實體具有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" ]
}
爲什麼是這種情況,這是預期的行爲,還是我做錯了什麼?
是因爲父實體(見下文)在子屬性上有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;
}
}
實體Child:
@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
嘿Cepr0,它是:https://github.com/simbro/spring-boot-practice-application - 雖然我想我已經想通了 - 見下文。 – simbro