JPA Annotations for many-to-many relation between objects of the same entity

前端 未结 1 694
梦如初夏
梦如初夏 2021-02-10 21:26

I want to implement a Role Hierarchy but am rather new to JPA Annotations.

I have a Role Entity with a name and an id(implicit via AbstractPersistable):

1条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 21:49

    Bidirectional relationship consists of owning and inverse sides.

    At the owning side you declare physical properties of the relationship:

    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "role_hierarchy", 
                joinColumns = { @JoinColumn(name = "role_id")}, 
                inverseJoinColumns={@JoinColumn(name="child_role_id")})  
    private List roles;
    

    At the inverse side you point at the corresponding owning side with mappedBy attribute:

    @ManyToMany(cascade = CascadeType.MERGE, mappedBy = "roles")
    private List children;    
    

    For many-to-many relationships it doesn't matter which side is the owning side (as long as you modify both sides consistently, since only changes at the owning side are propagated to the database).

    See also:

    • 2.2.5.3.2. Many-to-many

    0 讨论(0)
提交回复
热议问题