JPA Annotations for many-to-many relationships between objects of the same object

I want to implement a role hierarchy, but pretty new to JPA Annotations.

I have a Role object with name and id (implicit through AbstractPersistable ):

 @Entity @Table(name="role") public class Role extends AbstractPersistable<Long> { private static final long serialVersionUID = 8127092070228048914L; private String name; 

Now I want to be able to define the following relationships:

  • A role can have many child roles.
  • A role can be a child of many roles.

How do I do this with Hibernate annotations? Can I define this inside the role object

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

Am I on the right track? What am I missing?

Many thanks for your help!


EDIT: - deleted because it was resolved -


EDIT 2:

It looks like I have an error in the application stack. At the model definition level, the role_hierarchy hierarchy is working fine, so ignore EDIT 1 ...

BUT: Both methods seem to work (this creates an m: n table entry, cascading and retrieving parents and children for an object):

  • my suggestion is to define a join column for both sides without mappedBy property in mappedBy annotation
  • as well as the definition of the owner side and the reverse side.

Who cares? Does it matter?

+4
source share
1 answer

Bidirectional communication consists of ownership and the reverse side.

On the ownerโ€™s side, you declare the 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; 

On the back, you indicate the corresponding side with the mappedBy attribute:

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

For many-to-many relationships, it does not matter which side is the owner side (if you change both sides sequentially, since only the changes on the owning side are propagated to the database).

See also:

+14
source

All Articles