JPA @ManyToMany - Cannot delete or update a parent row: a foreign key constraint fails

Think how can JPA solve the many-to-many relationship.

I guess it creates table User, table Role and table user_role that contains references (foreign keys) to user and to role.

Now, if you want to remove role you have to remove all references of this role being held by users. In order to do this you have to iterate over all users that have such role and remove it from this user's role list. Then you can safely remove the role.

BTW once you solve this problem you will probably have the next one with Permission. So, if i were you I'd temporarily remove the permissions field from Role make the role deletion working and then restore the permissions to sole new problems if exist.


Try adding CascadeType.REMOVE to your mappings:

@ManyToMany(cascade= {CascadeType.PERSIST, CascadeType.REMOVE}, fetch=FetchType.EAGER)
private List<Role> roles = new ArrayList<Role>();

@ManyToMany(cascade= {CascadeType.PERSIST, CascadeType.REMOVE}, fetch=FetchType.EAGER)
private Set<Permission> permissions = new HashSet<Permission>();

In this way, children entities don't have to be removed before parent, so you could delete a Role without deleting its Permissions before.


I got this one fixed by,

changing some table names (maybe those names were reserved words in MySQL?)

e.g: "admins" instead of "admin"

@Table(name = "admins")
public class Admin extends TrackedEntity {

}

and by changing:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

for:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

in application.properties