JPA: foreign key constraint for deletion

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?

+4
source share
2 answers

One of your private Set<Images> imagesShared or private Set<Images> imagesLiked should have a link to the image you are trying to delete.

You will need to skip everything and remove the link to the image before deleting it.

EDIT:

To answer the second question.

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

works because you clear links to images stored in userAccount by calling userAccount.getImagesShared().clear()

Previously, what you did was simply delete the files stored in this image, and not delete the images from the userAccount object userAccount .

+6
source

private Set<Images> imagesLiked has a foreign key reference to IMAGES ( ID ), so if you are trying to delete private Set<Images> imagesShared; without deleting private Set<Images> imagesLiked; .

So try deleting images also marked

 image.setImagesLinked(null); 
0
source

All Articles