I have two entities Item, User
Code:
class User
{
@OneToMany(mappedBy="uploadedBy", cascade=CascadeType.ALL)
List<Item> uploadedITems;
@ManyToMany
List<Item> bookmarkedItems;
}
class ITem
{
@ManyToOne
User uploadedBy;
}
OneToMany bidirectional relationship between User And Item through User.uploadedItems & Item.uploadedBy. A user can upload multiple Items. If a user is deleted, his uploaded Items should also be deleted
ManyToMany unidirectional relationship between User And Item through User.bookmarkedItems. A user can bookmark multiple Items uploaded by some other user.
Problem is:
Action=Delete User
Expected Behavior:User is deleted along with Items uploaded by him. If deleted Item is bookmarked by some other user, that user's bookmarkedList should be changed and that ITem should be removed from that List.
Behavior happening:On deletion of cascaded Item, when item is to be deleted, an exception occurs "Deletion of Item failed in table USER_ITEM as Foreign key of item is still referred in the table" because deleted ITem is bookmarked by some other user and that other user's bookmarked list is not altered hence Data Integrity Violation.
I think I am missing some annotation to let that thing happen.
Can you guys please help me with this issue? How this can be corrected?
One more thing is, in case I don't want cascade deletion to happen, same kind of error will be thrown because some uploadedItem will be still referring deleted USer through foreign key. How to correct this scenario also? @NotFound(action=IGNORE) is the answer?