Spring Data Rest - 只能在一个方向上创建嵌套实体

Spring Data Rest - can only create nested entities on one direction

我对 Spring 启动/Spring 数据有疑问,我只能在一个方向上创建嵌套实体。

我有两个实体,Parent 和 Child,Parent 与 Child 实体有一对多关系。

如果我创建一个 Child,方法是:

POST http://localhost:8080/children
{
    "name": "Tenzin"
}

然后通过这样做创建一个 Parent:

POST http://localhost:8080/parents
{
    "name": "Fred and Alma",
    "children": [ "http://localhost:8080/children/1" ]
}

没用。

但是,如果我先创建parent,然后通过这样做创建一个新的child,它确实有效:

POST http://localhost:8080/children
{
    "name": "Jacob",
    "parent": [ "http://localhost:8080/parents/1" ]
}

为什么会这样,这是预期的行为还是我做错了什么?

是不是因为Parent实体(见下文)在children属性上有cascade=ALL?

Parent实体:

@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;
    }
}

在您的示例中,child 是关系芯片的所有者(它保存在数据库的 child table 中)。我认为有问题。 Spring Data Rest 将 child object 加载到 "children" 字段中,但不知道它还应该更改 child 的 "parent" 字段=]仁object。 (另见 )。

您可以通过捕获 Spring 数据休息事件 (http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events) 并手动设置 "parent" 字段来解决此问题。

参见上面 Benkuly 的回复,基本上,协会必须有所有者,任何关系都必须存在所有者。请参阅 Hibernate 文档:

https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping-association

The association may be bidirectional. In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side. In our case, this is passport. As you can see, you don't have to (must not) declare the join column since it has already been declared on the owners side.