Spring boot Spring Data Rest-只能在一个方向上创建嵌套实体
我对Spring引导/Spring数据有一个问题,即我只能在一个方向上创建嵌套实体 我有两个实体,父实体和子实体,父实体与子实体之间有一个单一的关系 如果我创建了一个子对象,请执行以下操作:Spring boot Spring Data Rest-只能在一个方向上创建嵌套实体,spring-boot,spring-data,spring-data-rest,Spring Boot,Spring Data,Spring Data Rest,我对Spring引导/Spring数据有一个问题,即我只能在一个方向上创建嵌套实体 我有两个实体,父实体和子实体,父实体与子实体之间有一个单一的关系 如果我创建了一个子对象,请执行以下操作: POST http://localhost:8080/children { "name": "Tenzin" } POST http://localhost:8080/parents { "name": "Fred and Alma", "children": [ "http://
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": "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;
}
}
在您的示例中,子级是relationchip的所有者(它保存在数据库的子表中)。我认为这是个问题。SpringDataREST将子对象加载到“children”字段中,但不知道它也应该更改子对象的“parent”字段。(另见)
您可以通过捕获Spring数据Rest事件()并手动设置“parent”字段来解决此问题。请参见上面的Benkuly回复,基本上,关联必须有一个所有者,该所有者必须存在才能存在任何关系。请参阅Hibernate文档: 关联可以是双向的。在双向关系中,其中一方(并且只有一方)必须是所有者:所有者负责关联列的更新。要声明一方不负责该关系,使用属性mappedBy。mappedBy是指所有者端关联的属性名称。就我们而言,这是护照。如您所见,您不必(不必)声明联接列,因为它已经在所有者端声明过
你能出示你的回购协议吗?嘿,Cepr0,它是:-虽然我想我已经弄明白了-见下文。嘿,Benkuly,谢谢你的回答,我忽略了vhild是这段关系的所有者这一事实。这就解释了正在发生的事情。谢谢你的帮助。