JPA坚持一对一的父母子女关系

JPA坚持一对一的父母子女关系

本文介绍了JPA坚持一对一的父母子女关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保留20个子实体的父实体,我的代码在下面

I want to persist parent entity with 20 child entities,my code is below

父母阶级

@OneToMany(mappedBy = "parentId")
private Collection<Child> childCollection;


儿童班


Child Class

@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循环? 可行吗还有其他可以自动保留父级和子级的方式或配置吗?

So if there are 20 child tables then I have to set parent reference in each of them for that I have to write 20 for loops? Is it feasible? is there any other way or configuration where I can automatically persist parent and child?

推荐答案

修复父类:

@OneToMany(mappedBy = "parent")

mappedBy 属性应指向关系另一侧的字段.正如 JavaDoc 所说:

mappedBy property should point to field on other side of relationship. As JavaDoc says:

此外,您还应该明确地在周期中持久保留子实体:

Also you should explicitely persist Child entity in cycle:

for(Child tha : parent.getChildCollection()) {
    ...
    getEntityManager().persist(tha);
    ...
}

Alan Hay 在评论中注意到,您可以使用级联功能,并让EntityManager自动持久保存所有子实体:

As Alan Hay noticed in comment, you can use cascade facilities and let EntityManager automatically persist all your Child entities:

@OneToMany(mappedBy = "parent", cascade = CascadeType.PERSIST)

您可以在弗拉德·米哈尔西娅(Vlad Mihalcea)的博客.

这篇关于JPA坚持一对一的父母子女关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:58