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
):
@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:
How would I do that with Hibernate annotations? Can I define this inside the Role Entity
@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?
Thank's a lot for your help!
EDIT: - removed as it has been solved -
EDIT 2:
Looks like I have some bug in my application stack. On the model defining level the role_hierarchy is working out just fine, so never mind EDIT 1...
BUT: Both ways seem to work (that is createing the m:n table entry, cascading delete and retrieval of parents and children for an entity):
mappedBy
property at the @ManyToMany
annotationWhat's the difference? Does it matter?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With