Search code examples
javahibernateforeign-keysmappingmany-to-many

Foreign keys in ManyToMany Java + Hibernate + MySQL


When I am trying to delete Role from the roles table with the help of Hibernate using its id it occurs an exception:

 com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`ewp`.`permissions`, CONSTRAINT `FK_sq51ihfrapwdr98uufenhcocg` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`))

Class User ... @NotNull @ManyToMany(fetch = FetchType.EAGER, targetEntity = Role.class) @JoinTable(name = "permissions", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")}) private Set<Role> roles; ...

Class Role ... @ManyToMany(fetch = FetchType.EAGER) private List<User> users; ...

When I add to Role

@JoinTable(name = "permissions", joinColumns = {@JoinColumn(name = "role_id")}, inverseJoinColumns = {@JoinColumn(name = "user_id")}) private List<User> users;

Roles deleted without exceptions. But I think that it can work without mapping in Role.


Solution

  • You either need to determine which side of the Many-To-Many owns the relationship or make sure that you alter both sides prior to removing the associated Role objects.

    As mentioned in the comments, you can imply ownership by adding a mappedBy attribute to either side of the relationship. By adding mappedBy="roles" to the Role entity, this will tell the persistence provider that the relationship is managed by the User object's roles property and thus to manipulate the relationship using its join-table mapping.