Null collections with orphanRemoval=true lead to "A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance"
Description
Activity
Israel Rios June 4, 2024 at 5:16 PMEdited
I got this on version 6.5.2 It worked fine in 6.4.4.
Алексей Кричевский September 13, 2018 at 4:02 PMEdited
Still exists for 5.2.17.Final Upd: exists in 5.3.6.Final
This is more like a bug: hibernate considers null collection not equal empty collection on merge operation.
Persist operation returns entity and keeps null for collection(I think bug is here), by contrast find returns entity with empty bag.
Such inconsistense leads to this error: merge operation loads entity with empty bag and compare it with new entity containing null. As a result empty bag becomes orphan.
Xin Jin July 24, 2017 at 7:44 AM
4.1.9 also exists this issue.
Andreas Benneke October 29, 2015 at 9:22 AM
Thank you for looking into this one.
I agree, but if legacy Hibernate needs it this way, I would expect a proper exception instead? This one is very misleading...
Steve Ebersole October 29, 2015 at 4:50 AM
This works as designed. In legacy Hibernate orphan-delete support (which way predates JPA) for collections required that the collection was never nulled. JPA does not say one way or the other.
At best, I think, this is an feature/enhancement request.
When you initialize the collection of an OneToMany relation with
orphanRemoval=true
withnull
, Hibernate fails to persist changes to a (re)loaded entity with the following exception:org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: ... at org.hibernate.engine.internal.Collections.processDereferencedCollection(Collections.java:114) at org.hibernate.engine.internal.Collections.processUnreachableCollection(Collections.java:67) at org.hibernate.event.internal.AbstractFlushingEventListener.flushCollections(AbstractFlushingEventListener.java:258) at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:103) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1335)
Things work however, if
the collection is initialized with an empty collection (instead of
null
)orphanRemoval is set to false
This may be related to https://hibernate.atlassian.net/browse/HHH-7726#icft=HHH-7726 and/or HHH-9935, but the null collection case is not covered there.
You may find a small stripped down test project on Github https://github.com/abenneke/sandbox/tree/master/hibernate-null-collection
Thank you!