JPA Persist parent and child with one to many relationship

前端 未结 5 550
我寻月下人不归
我寻月下人不归 2020-12-24 08:13

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

Parent Class

@OneToMany(mappedBy = \"parentId\")
private Collection

        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 08:34

    Fix your Parent class:

    @OneToMany(mappedBy = "parent")
    

    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);
        ...
    }
    

    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)
    

    More details about cascades (and JPA itself) you can find in Vlad Mihalcea's blog.

提交回复
热议问题