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.