如何使用Spring data JPA保存双向关联而不进行级联?

问题描述 投票:0回答:2

假设我在父子之间有双向一对多关联,映射如下:

Parent.java:

@Entity
public class Parent {

    @Id
    private Integer id;

    @OneToMany(mappedBy = "parent")
    private List<Child> childs = new ArrayList<>();
    ...

和 Child.java:

@Entity
public class Child {

    @Id
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    ...

当我运行这段代码时

    Parent parent = new Parent(1);
    Child child = new Child(1);
    Child child2 = new Child(2);
    child.setParent(parent);
    child2.setParent(parent);
    parent.getChilds().add(child);
    parent.getChilds().add(child2);

    parentRepository.save(parent);

我遇到异常

    Unable to find Child with id 1

先救孩子也无济于事,只是例外情况不同

java spring hibernate jpa
2个回答
0
投票

嗯,我很抱歉发布了不确定的答案,但由于声誉原因我无法发表评论。 我认为您遇到了交叉引用问题,因为只需从子级引用父级,您就可以通过简单的查询获取父级拥有的子级。相反,您交叉引用子关联会导致许多对象问题。如果您愿意,我可以给您发布一个类图以获得更好的解释。希望有帮助


0
投票

尝试

@OneToMany(mappedBy = "parent", cascade={CascadeType.PERSIST})
private List<Child> childs = new ArrayList<>();

(另请参阅 JPA @ManyToOne 与 CascadeType.ALL 例如)

© www.soinside.com 2019 - 2024. All rights reserved.