且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-02-06 00:44:46

修复父类:

@OneToMany(mappedBy = "parent")

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

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

拥有关系的字段.除非关系是单向的,否则为必需.

The field that owns the relationship. Required unless the relationship is unidirectional.

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

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)的博客.