我有以下关系
Class UserAccount{
//Other fields
@OneToMany(mappedBy = "userAccount", cascade = CascadeType.REMOVE)
private Set<Images> imagesShared;
@ManyToMany
@JoinTable(name = "USER_LIKES", joinColumns = @JoinColumn(name = "USER_NAME"), inverseJoinColumns = @JoinColumn(name = "ID"))
private Set<Images> imagesLiked;
}
Class Images{
//other fields
@ManyToMany(mappedBy = "imagesLiked")
private Set<UserAccount> likes;
}
在这些行之后我得到一个例外
Hibernate: delete from IMAGES where ID=?
Hibernate: delete from COMMENTS where COMMENT_ID=?
Hibernate: delete from COMMENTS where COMMENT_ID=?
Hibernate: delete from COMMENTS where COMMENT_ID=?
Hibernate: delete from COMMENTS where COMMENT_ID=?
Hibernate: delete from COMMENTS where COMMENT_ID=?
Hibernate: delete from IMAGES where ID=?
例外:
Cannot delete or update a parent row: a foreign key constraint fails (`testdb`.`USER_LIKES`, CONSTRAINT `FKC6704E28B4E3D8B` FOREIGN KEY (`ID`) REFERENCES `IMAGES` (`ID`))
据我了解,这发生在 JPA 尝试删除imagesShared
. 我试过这样做:
for (Images image : userAccount.getImagesShared()){
image.setLikes(null);
}
em.remove(account);
但同样的错误。任何人?
更新
当我添加这一行时,它工作正常。
for (Images image : userAccount.getImagesShared()){
image.setLikes(null);
}
userAccount.getImagesShared().clear();
em.remove(account);
但是 JPA 所做的删除操作和我所做的有什么区别呢?