【发布时间】:2016-05-13 21:12:18
【问题描述】:
我想保留具有 20 个子实体的父实体, 我的代码在下面
父类
@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 个 for 循环? 可行吗?有没有其他方法或配置可以自动持久化父子关系?
【问题讨论】:
-
这似乎更像是一个 JSON 问题而不是 JPA 问题。如果您的 JSON 未编组以便设置正确的关系,那么在保存父级时让子级持久化只需将相关的级联选项添加到 @OneToMany(假设您的映射是正确的)
-
如果您没有发回 Child->Parent 关系,或者它没有在从 JSON 构建的内容中设置,那么是的,您需要在每个子实体中手动设置它。另一种方法是使关系单向:从 OneToMany 中删除 mappedby="parent" 并指定一个 JoinColumn。这将导致 OneToMany 在子表中设置外键,而不是通过子表对其父表的引用来设置(然后您应该删除子表的父属性和映射)
-
关于@Chris 所说的,仅提及关联单向
@OneToMany的推荐方法是使用@JoinTable。来自文档:unidirectional one-to-many association on a foreign key is an unusual case, and is not recommended. You should instead use a join table for this kind of association.
标签: jpa one-to-many