Spring JPA Many for many: delete the object, delete the entry in the connection table, BUT DO NOT REMOVE the other side

I have this use case:

  • I have users.
  • I have groups.
  • There is an N: N relationship between users and groups.
  • I can not delete users.
  • If I delete a group, users of this group should not be deleted.

User side:

@ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
                    name = "USERS_GROUPS",
                    joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "ID") ,
                    inverseJoinColumns = @JoinColumn(name = "GROUP_ID", referencedColumnName = "ID") )
    private List<GroupJPA> groups;

Group side:

@ManyToMany(mappedBy = "groups", cascade = CascadeType.ALL)
private List<UserJPA> returnsList;

If I delete a group from the list of user groups, the group will be deleted from the list of users, it will be deleted from the connection table and will not be deleted from the Group table. This is the behavior of desire.

But, if I delete the whole group, it will happen that all links in the connection table will be deleted, BUT ALSO Users will also be deleted! It cannot be.

I am using 4.3.5.Final and Spring 4.3.0.RELEASE.

+4
1

cascade = CascadeType.ALL

@ManyToMany(mappedBy = "groups", cascade = CascadeType.ALL)
private List<UserJPA> returnsList;

. , ... UserJPA.

, , . UserJPA, , .

Cascading UserSide, :

removeFromGroup(Group group) {
    user.getGroups().remove(group);
    groups.removeUser(this);
}

, .

+2

All Articles