I have the following ratio
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; }
I get an exception after these lines
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=?
An exception:
Cannot delete or update a parent row: a foreign key constraint fails (`testdb`.`USER_LIKES`, CONSTRAINT `FKC6704E28B4E3D8B` FOREIGN KEY (`ID`) REFERENCES `IMAGES` (`ID`))
From my understanding, this happens when the JPA tries to remove imagesShared . I tried to do this:
for (Images image : userAccount.getImagesShared()){ image.setLikes(null); } em.remove(account);
But the same mistake. Is anyone
UPDATE
When I add this line, it works fine.
for (Images image : userAccount.getImagesShared()){ image.setLikes(null); } userAccount.getImagesShared().clear(); em.remove(account);
But what is the difference between the delete operation performed by JPA and what am I doing?
source share