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

前端 未结 1 707
借酒劲吻你
借酒劲吻你 2021-02-10 20:59

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条回答
  • 2021-02-10 21:57

    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<Role> roles;
    

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

    @ManyToMany(cascade = CascadeType.MERGE, mappedBy = "roles")
    private List<Role> 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)
提交回复
热议问题