[英]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.