This is one of those errors that shouldn’t happen.  However, due to lazy-loading Hibernate is smart enough to realize you have loaded an object once before during a session and does not attempt to do so again – even though you have deleted it during the session and it should not be a part of any collection anymore.

A workaround I have started to use is to set the version of objects I am deleting to -1 and the later in time when I am about to persist or merge an object I check to see if the version is still valid first.  This includes objects I delete by hand and objects that may be about to be cascade deleted that I may later on attempt to persist/merge.

I am sure there is a smarter way to do this, but this works well.

One thing I was toying with was the error message that comes up for this exception usually mentions the object using the standard notation of <object>@<hashcode> where the hashcode that prints out is null.  This is a little wierd as the hashcode that I have in my entities is a int not an Integer, so I can’t tell how to poke at a null int to get the same effect as my invalid version/deleted flag.