简体   繁体   中英

JPA- ManyToMany relation the delete operation removes all entities from secondary table

I am using Spring data JPA and postgres database. I have two entities namely group and user. I have created repository using Spring's CrudRepository inteface.

@Entity
public class Group { 
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(
        name="group_user_bridge", 
        joinColumns=@JoinColumn(name="joinTbl_groupid", referencedColumnName="groupid"), 
        inverseJoinColumns=@JoinColumn(name="joinTbl_agentid", referencedColumnName="userid")
        )
private Set<User> users;
....
}

class User

@Entity
public class User {

@ManyToMany(mappedBy="users",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
private List<Group> groups;
.....
 }

Repository.save : Works fine.

  @Test
  public void addGroup(){
        Group hg = new Group();

        User h1 = new User();
        User h2 = new User();
        some setters for user entity object

        hg.setName("testGroup");
        ... some setters for groups

        HashSet<User> groupMembers = new HashSet<User>();
        groupMembers.add(h2);
        groupMembers.add(h1);
        hg.setGroupMembers(groupMembers);

        hg = groupRepository.save(hg);

Question

When I delete the group using groupRepository.delete(groupEntity), it deletes the group, the association of group and users from join table.
but it also deletes the users from user table. In fact the users records should not get deleted .

How to prevent user deletion here?

I am using @SQLDelete annotation for soft deleting the group and user records. but I am not able to achieve the same for the join table records. The records in the join table gets hard deleted from the table which I want to prevent.

How can we prevent hard delete of the join table records?

You currently to have this annotation in the User and Group classes:

@ManyToMany(cascade=CascadeType.ALL)

The Hibernate docs indicate that this will cause cascading of the following operations: save, delete, update, evict, lock, replicate, merge, persist

So it makes sense that when you delete the Group instance, the delete cascades to the User instances.

Consider changing the annotation to something like:

@ManyToMany(cascade=CascadeType.SAVE_UPDATE)

Or whatever is appropriate for your application.

Optionally, you can remove the User instances from the Group prior to deleting the Group .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM