JPA Persist parent and child with one to many relationship

前端 未结 5 568
我寻月下人不归
我寻月下人不归 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:29

    Generally, @JoinColumn indicates that the entity is the owner of the relationship & mappedBy indicates that the entity is the inverse of the relationship.

    So, if you are trying like following

    @OneToMany(mappedBy = "parent")
    private Collection childCollection;
    

    That means it is inverse of the relationship and it will not set parent reference to its child.

    To set parent reference to its child, you have to make the above entity owner of the relationship in the following way.

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn
    private Collection childCollection;
    

    You need not set any child reference because above code will create a column in the child table.

提交回复
热议问题