![](/img/trans.png)
[英]Spring Data JPA causes EntityExistsException with cascading save
[英]How to save bidirectional association without cascading using Spring data JPA?
假设我在父子之间有双向的一对多关联,映射如下:
父.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
先救孩子也无济于事,只有例外不同
好吧,我很抱歉发布了一个不确定的答案,但我不能发表评论的声誉原因。 我认为您有一个交叉引用问题,因为只需从孩子那里引用父母,您就可以通过简单的查询获得父母拥有的孩子。 相反,您交叉引用导致许多对象问题的子关联。 如果您愿意,我可以向您发布一个类图以获得更好的解释。 希望能帮助到你
尝试
@OneToMany(mappedBy = "parent", cascade={CascadeType.PERSIST})
private List<Child> childs = new ArrayList<>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.