I have one Role
that can refer to a Set of Permission
s.
How can I annotate both classes to fit composition (not aggregation) where:
Permission
continues to exist if a Role
is
deleted ?Role
continues to exist if it has no Permission
s.P.S: How should this be handled with merging/persisting ?
This is a ManyToMany
relationship annotated with @ManyToMany
. If it is required to have a unidirectional ManyToMany
then just annotate the member field or getter method (depending on the access type field or property respectively) of the Role
class related to Permission
. If you need bidirectional
relationship then you will have to annotate both classes and specify the mappedBy
annotation attribute on the non-owning/target side, the Permission
class.
To achieve this relationship a join table
will be created if not already exists ( if it exists a @JoinTable
may be required to specify exact table name and column names).
Regarding persistence and merging, when a Role
persists/merges the associated Permissions
will also be persisted/merged and the associated entries in the join table will be created as in a many-to-many relationship the owner side actions are cascaded by default (the owner side is the side without the mappedBy
attribute).
So the setup for a bidirectional many-to-many would be something like,
@Entity
public class Role {
....
@ManyToMany
private Set<Permission> permissions;
....
@Entity
public class Permission{
.....
@ManyToMany(mappedBy="permissions")
private List<Role> roles;
....
also check out the spec http://download.oracle.com/otndocs/jcp/persistence-2_1-fr-spec/index.html and this wonderful book http://www.apress.com/9781430219569