JPA Hibernate many-to-many cascading
As already indicated, make the group owner of the relation if you don't need to cascade from the user side.
Then, try to use cascade=CascadeType.MERGE
to not delete cascade the user when you delete the group.
Seeing the problem from another angle :
You could add FK constraints to you many-to-many mapping table. Actually you should always have FKs in you DB for data integrity reasons. In this case for example, at least the user could not be deleted while silently leaving orphan rows in the mapping table.
When you have FKs, you can specify the on delete cascade referential action on the constraints, and the DB will manage the automatic deleting of the mapping table, but not of the entity, like you asked for.
The way you have it mapped, the User
is the managing side of the relationship, therefore it will be responsible for updating the join table.
Change the JoinTable
mapping from User
to Group
, and make the groupList
property of User
so it has the mappedBy
attribute. That will change the group to the managing side of the relationship, and make persist/update calls to the group manage the join table.
But take note of that, you won't be able to simply add a group to a user, save the user, and continue, you'll instead have to add a user to the group and save the group to see the changes, but having the bi-directional many-to-many hopefully you'll be closely managing that relationship anyway.
You can do something like this
@PreRemove
private void removeMembers() {
this.memberList.clear();
}