gstackoverflow
gstackoverflow

Reputation: 37078

Why it is not alllowable to set a new collection in hibernate?

In some cases in my experience I encountered that following usage is wrong:

entity.setElements(newCollection);

And I get error like this:

"A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance".
So I have to rewrite it like this:

entity.getElements().clear();
entity.getElements().addAll(newCollection)

Can you please explain why does it happen?

Is it only orphan related issue?

Upvotes: 6

Views: 789

Answers (1)

Benoit
Benoit

Reputation: 5394

When you perform entity.setElements(newCollection) in java, you actually replace the existing collection with a new one. What happen to elements that were in the existing collection ? They become orphan. Then the garbage collector comes into action and removes (i.e. free the memory used by) the orphan objects. All this occur in RAM, it's a thread running in the JRE, no database involved so far.

Unfortunately there is nothing like a garbage collector in relational databases. You (or in this case Hibernate) have to explicitly delete orphan records using a delete statement.

Hibernate will therefore trigger delete statement for each Collection.remove() or Collection.clear().

Also, there is no way for Hibernate to intercept the JRE garbage collector action to trigger it's own set of delete statements. So when you do entity.setElements(newCollection), Hibernate detects that previous collection has been garbage collected, but it's too late, it has no reference anymore to the oprhan objects, thus it cannot make the delete statements.

Upvotes: 6

Related Questions