JPA @ManyToMany - 无法删除或更新父行:外键约束失败
2022-09-04 20:55:11
我有实体:
@Entity
public class User {
@ManyToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)
private List<Role> roles = new ArrayList<Role>();
@Entity
public class Role {
@ManyToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)
private Set<Permission> permissions = new HashSet<Permission>();
执行删除/移除操作时,将引发以下异常:
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`test`.`user_role`, CONSTRAINT `FK_USER_ROLE_roles_ID` FOREIGN KEY (`roles_ID`) REFERENCES `role` (`ID`))
生成的联接表和外键似乎存在问题。
如何修复此问题,以便删除角色?
编辑:
导出的 SQL 显示以下内容:
CREATE TABLE IF NOT EXISTS `user_role` (
`User_ID` bigint(20) NOT NULL,
`roles_ID` bigint(20) NOT NULL,
PRIMARY KEY (`User_ID`,`roles_ID`),
KEY `FK_USER_ROLE_roles_ID` (`roles_ID`)
)