我要坚持父实体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