Reputation: 1197
I have two entities Users and Groups , associated with Many-To-Many
a user belongs to many groups and he know them (navigabilite_1)
a group contain many users and he know them (navigabilite_2)
I want when I delete a user only user and the relation(in join table) get deleted not the group and the same for deleting groups should not affect user only the group and the relation
What kind of association should I use Bidirectional or two unidirectional ,and where should I put the cascade on delete ?
Upvotes: 0
Views: 38
Reputation: 691983
You should use a bidirectional association, and you shouldn't use any cascade, since cascading would also delete the entity at the other side of the association.
Assuming User.groups
is the owner side of the association, deleting a group would be done using
for (User user : group.getUsers()) {
user.getGroups().remove(group);
}
// optional:
group.getUsers().clear();
session.delete(group);
And deleting a user would be done using
// optional:
for (Group group : user.getGroups()) {
group.getUsers().remove(user);
}
user.getGroups().clear();
session.delete(user);
Upvotes: 1