I\'m currenetly trying hard to delete an entity, that is involved in various relations (Only @ManyToOne
) - However, Hibernate does not delete anything - after c
I figured out the problem(s) - Actual there have been two of them: (Leaving this here, if somebody stumbles across a similar issue)
As I mentioned, the deletion should have happened in an ajax request. Therefore, simple calling
em.remove(instanceOfE6);
resulted in an java.lang.IllegalArgumentException: Removing a detached instance
exception. So, I tried the approach using merge:
em.remove(em.merge(instanceOfE6));
which did not produce an error - but simple didn't work. I enabled trace-logging for hibernate as mentioned in this post: JPA/Hibernate remove entity sometimes not working to figure out what went wrong, and indeed, trying to remove the entity resulted in:
TRACE [org...DefaultPersistEventListener] un-scheduling entity deletion ...
Obviously the entity to remove is still connected to other entities, which lead to the problem that hibernate aborted the deletion, so i tried to remove the relations before deletion.
As you can see from the example of E6
, I used @ManyToOne(optional = false)
, which means I cannot set the outgoing references to null, or it will cause exceptions when calling merge
.
My first attempt to clean the relations was only "cleaning the sets", because I assumed that cleaning the outgoing relations of the entity I want to delete is not required. It is not, but i'll outline this in detail a little later:
So, the code now looked like
instanceOfE6.getE1().getE6s().remove(instanceOfE6);
instanceOfE6.getE2().getE6s().remove(instanceOfE6);
instanceOfE6.getE3().getE6s().remove(instanceOfE6);
instanceOfE6.getE4().getE6s().remove(instanceOfE6);
instanceOfE6.getE5().getE6s().remove(instanceOfE6);
em.remove(em.merge(instanceOfE6));
Same issue: deletion aborted. I missed the obvious fact, that calling merge
will ofc. restore the entries inside the sets i just removed, because instanceOfE6 STILL had it's not nullable-references on the other entities. Therefore deletion was aborted again.
Finally the solution ofc. was to do the the merge before removing the references and the final deletion:
if (!em.contains(instanceOfE6)){
instanceOfE6 = em.merge(instanceOfE6);
}
instanceOfE6.getE1().getE6s().remove(instanceOfE6);
instanceOfE6.getE2().getE6s().remove(instanceOfE6);
instanceOfE6.getE3().getE6s().remove(instanceOfE6);
instanceOfE6.getE4().getE6s().remove(instanceOfE6);
instanceOfE6.getE5().getE6s().remove(instanceOfE6);
em.remove(instanceOfE6);
I'm not quite sure if I explained everything 100% accurate, but at least I can reproduce and fix the Issue by changing the code back and forth.