我要堅持父實體20個子實體, 我的代碼如下JPA堅持家長和孩子有一對多的關係
父類
@OneToMany(mappedBy = "parentId")
private Collection<Child> childCollection;
子類
@JoinColumn(name = "parent_id", referencedColumnName = "parent_id")
@ManyToOne(optional=false)
private Parent parent;
String jsonString = "json string containing parent properties and child collection"
ObjectMapper mapper = new ObjectMapper();
Parent parent = mapper.readValue(jsonString, Parent.class);
public void save(Parent parent) {
Collection<Child> childCollection = new ArrayList<>() ;
for(Child tha : parent.getChildCollection()) {
tha.setParent(parent);
childCollection.add(tha);
}
parent.setChildCollection(childCollection);
getEntityManager().persist(parent);
}
所以如果有20個子表,那麼我必須在它們的每一箇中設置父引用,以便我必須爲循環寫入20個引用? 可行嗎?有沒有其他方式或配置可以自動堅持父母和孩子?
這似乎是一個比JPA問題更多的JSON問題。如果你的JSON被解組,那麼設置適當的關係,然後讓孩子在保存父對象時保持不變,只需將相關的級聯選項添加到@OneToMany(假設你的映射是正確的) –
如果你沒有發送孩子 - >父親關係回來,或者它沒有設置從JSON構建的內容,那麼是的,你需要在每個子實體中手動設置它。另一種方法是單向關係:從OneToMany中移除mappedby =「parent」,而是指定一個JoinColumn。這將導致OneToMany在子表中設置外鍵,而不是通過子對其父項的引用來設置(然後您應該刪除子項的父屬性和映射) – Chris