Merge entity with @OneToMany attributes leading to javax.persistence.EntityNotFoundException: No row with the given identifier exists

Is Hibernate meant to do the inserts before the deletes in method doWork?

Yes. To preserve the order of operations the insert is done before delete as explained in this article. If you bump into such issue, it means you were doing the merge like this:

  • you try to clear the collection
  • then you re-add back the entries sent from the client

That’s not a good approach. You should do the merging from the incoming collection and the one in the database like this:

  • add the new entries
  • update the remaining ones
  • delete the ones that are no longer found in the incoming collection

For more details, check out this article.

Will removing the snapshots on the PersistantSet have any strange sideeffects?

Better do what I advised you already instead of trying to modify Hibernate internals.

Is there a better way to implement the given business process?

Yes, as already mentioned.

We recently upgraded Hibernate from 3.6.4 to 5.2.12 and I think the exceptions didn’t occure back in the old version

Hibernate 3.6 is 7 years old now. The flush operation order hasn’t changed for a very long time so this issue might be replicating on 3.6 as well. On the other hand, there are many performance improvements in 5.x that you will not find in 3.6.