Deleted object would be re-saved by cascade (remove deleted object from associations)
Solution 1:
The solution is to do exactly what the exception message tells you:
Caused by: org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)
Remove the deleted object from an associations (sets, lists, or maps) that it is in. In particular, i suspect, from PlayList.PlaylistadMaps
. It's not enough to just delete the object, you have to remove it from any cascading collections which refer to it.
In fact, since your collection has orphanRemoval = true
, you don't need to delete it explicitly. You just need to remove it from the set.
Solution 2:
problem solved after changing the FetchType to Lazy
Solution 3:
If you don't know, which collection holds your object
In my case it was really hard to apply TomAnderson's solution, since I didn't know what is the collection, which holds a link to an object, so here's the way to know, which objects holds the link to the deleted one: in the debugger you should enter the lowest execution stack level before the exception is thrown, there should be a variable called entityEntry
, so you get a PersistenceContext
object from this variable: entityEntry.persistenceContext
.
For me persistenceContext
was an instance of StatefulPersistenceContext
and this implementation has private
field parentsByChild
, from which you can retrieve information about the collection, which contains the element.
I was using Eclipse debugger, so it was kinda hard to retrieve this private field in a straight way, so I used Detail Formatter
(How can I watch private fields of other objects directly in the IDE when debugging?)
After getting this information, TomAnderson's solution can be applied.
Solution 4:
Some how all the above solutions did not worked in hibernate 5.2.10.Final.
But setting the map to null as below worked for me:
playlist.setPlaylistadMaps(null);
Solution 5:
I encountered this exception message as well. For me the problem was different. I wanted to delete a parent.
In one transaction:
- First I called up the parent from the database.
- Then I called a child element from a collection in the parent.
- Then I referenced one field in the child (id)
- Then I deleted the parent.
- Then I called commit.
- I got the "deleted object would be resaved" error.
It turns out that I had to do two separate transactions. I committed after referencing the field in the child. Then started a new commit for the delete.
There was no need to delete the child elements or empty the collections in the parent (assuming orphanRemoval = true
.). In fact, this didn't work.
In sum, this error appears if you have a reference to a field in a child object when that object is being deleted.