A flush during a transaction can cause the org.hibernate.engine.spi.ActionQueue.InsertActionSorter#sort implementation to produce an incorrect ordering with subsequent constraint violation.
A simple test case is attached.
If you find any use case that fails, let me know. The more tests we have, the better it gets.
This fixed a number of problems, but some remain – in particular, we're seeing this in the logs now:
After this, we see the (not unexpected) constraint error.
Working to isolate this case now.
If you see that warning, then it means the batch could not be sorted in twice the number of statements. I added a threshold because I didn't want to risk it run indefinitely due to a circular dependency.
So, this can be caused by:
1. A circular @ManyToOne dependency: Parent -> Child, Child -> Parent
2. A bug which cannot detect the dependency between parent - child elements
I need a replicating test case for it.
Working on whittling down to a standalone test case now – not sure which of the two cases this one falls into, yet.
Fixed in 5.1 branch as well.