JPA:删除时的外键约束

时间:2013-04-10 05:31:53

标签: java mysql hibernate jpa

我有以下关系

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执行的删除操作与我的操作之间有什么区别?

2 个答案:

答案 0 :(得分:6)

您的private Set<Images> imagesSharedprivate Set<Images> imagesLiked之一必须引用您要删除的图片。

在删除之前,您必须遍历所有内容并删除图像引用。

编辑:

回答你的第二个问题。

 for (Images image : userAccount.getImagesShared()){
            image.setLikes(null);
        }
userAccount.getImagesShared().clear();
em.remove(account);

有效,因为您正在通过调用userAccount

清除userAccount.getImagesShared().clear()中存储的图像引用

以前您所做的只是删除存储在该图片中的图片,而不是从userAccount对象本身删除图片。

答案 1 :(得分:0)

private Set<Images> imagesLikedIMAGESID)的外键引用,因此如果您尝试删除private Set<Images> imagesShared;而不删除private Set<Images> imagesLiked;

因此,请尝试删除imagesLinked

image.setImagesLinked(null);