Hibernate cannot delete


#1

I’m using hibernate.

@Entity
@Table(name=“user”)
public class User{
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = “user_roles”, joinColumns = @JoinColumn(name = “user_id”, referencedColumnName = “id”), inverseJoinColumns = @JoinColumn(name = “role_id”, referencedColumnName = “id”))
private List roles;
}

@Entity
@Table(name=“role”)
public class Role {
@ManyToMany(mappedBy = “roles”, fetch = FetchType.LAZY)
private List users;
}

through repository.delete Role
Cannot delete the association table relationship.Exception:
Cannot delete or update a parent row: a foreign key constraint fails


#2

Prior to deleting a Role, you have to remove it from all Users.

So, iterate role.users and remove the role from each User.roles.

Or, execute a native SQL:

delete from user_roles where role_id = :roleId