1

I have the following entities. I want to be able to delete a User and any entry in the UserGroupMap that contains that User should also get deleted. However everytime I try deleting a user that also has a entry in UserGroupMap I am getting the following error.Cannot delete or update a parent row: a foreign key constraint fails How can I achieve this behavior?

@Entity
public class User {

   @Id
   private Long id;

   @Column
   private String name;

   @ManyToMany(mappedBy = "users", cascade = CascadeType.All)
   private Set<Group> groups;

 }


@Entity
public class Group {

   @Id
   private Long id;

   @Column
   private String type;

    @ManyToMany
    @JoinTable(name = "UserGroupMap", 
            joinColumns = @JoinColumn(name = "groupId", referencedColumnName = "id"), 
            inverseJoinColumns = @JoinColumn(name = "userId", referencedColumnName = "id") )
   private Set<User> users;

 }
sideshowbob
  • 304
  • 6
  • 23

3 Answers3

0

You should add (cascade=CascadeType.REMOVE) to your many to many relationship

like this example

@ManyToMany(cascade=CascadeType.REMOVE)
0

From what I understand looking at the entities, Group should not be deleted and the User belongs to a Group.

This means the Group entity is the parent side. When removing the User you need to remove it from the Group side.

Create a method on the Group entity called "remove" which takes a User parameter which is the user you want to remove.

public void remove(User user) {

    for(Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
        User removeUser = iterator.next();
        /*
         * you can check here if the user is equal to the parameter user
         * if equal remove
         */
        if(removeUser.equal(user)) {
           removeUser.setGroup(null);
           iterator.remove();
        {
    }
}
Rentius2407
  • 1,108
  • 2
  • 11
  • 29
-1
@Entity
public class User {

   @Id
   private Long id;

   @Column
   private String name;

   @ManyToMany(mappedBy = "users", cascade = CascadeType.All, orphanRemoval=true)
   private Set<Group> groups;

 }

orphanRemoval option should handle the deletion of the childs

PeaceIsPearl
  • 329
  • 2
  • 6
  • 19
  • 1
    there is no orphanRemoval for ManyToMany – sideshowbob May 11 '16 at 12:42
  • If you are using hibernate then @OnDelete action would be useful to you. http://docs.jboss.org/hibernate/stable/annotations/api/org/hibernate/annotations/OnDelete.html @OnDelete(action=OnDeleteAction.CASCADE) – PeaceIsPearl May 11 '16 at 21:40
  • like @kittels said there is no orphanRemoval in manytomany since hibernate would have to check if each record has a relation in the other table, which is not possible. – Sidharth Ramesh Sep 21 '18 at 09:41