I have an entity that has a ManyToMany relationship with itself:
@Entity
public class User {
@Id
private Long id;
@ManyToMany
private List<User> friends;
}
How can I delete a user without deleting all of his friends? I cannot use cascading deletes obviously. If I try to delete the user without cascading I get a this error: “Cannot delete or update a parent row: a foreign key constraint fails”
Normally with
ManyToManywe will map data in different tables, and the delete won’t create much of a problem. I feel your case is different an you are having a self relationship. I think you need to use some other ways to perform this action.How can I delete a user without deleting all of his friends?The below option is one of them.Considering your special mapping,
List<User>inUser, you should be only updating the mapping table references, and not deleting anything from theUsertable. Because they may have some otherUseras friends and that can create problems.