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?
source share