Using Order Inserts and @DynamicUpdate together on a table that has a foreign key relationship to itself causes constraint violation exceptions

Description

If you turn on ORDER_INSERTS (a.k.a. hibernate.order_inserts), so that insertions are batched, and have a table that has a foreign key relationship to itself (so some row entries are children of other row entries), and have the @DynamicInsert annotation on this table, then the code in BatchingBatch.performExecution that iterates through the set of statements for the batch:

can cause insertions to get reordered: it selects insertions out of the batch that match each SQL statement in turn, so insertions that use the same statement are performed in the original (as persisted) order, but insertions that use different SQL statements happen in arbitrary order. If a single flush included inserting a parent and then its child, but the set of columns being inserted for the parent and the child differ in a way that cause them to be inserted using different SQL statements, then this reordering of the insertions can sometimes cause the child to get inserted before the parent, causing a constraint violation. The only workarounds for a user are to either turn off the ORDER_INSERTS setting for the session, or remove the @DynamicInsert annotation from the table, both of which can have significant performance costs.

We didn't run into this issue when we were using Hibernate 4.3.10 (with ORDER_INSERTS enabled and @DynamicInsert on all tables), but it showed up many times in our unit tests during our effort to update to 5.2.15. So this appears to be a regression some time between 4.3.10 and 5.2.15 (I haven't debugged it under 4.3.10 to figure out how it used to work). I don't currently have any of our unit tests converted into a test case simple enough to submit.

There may well be a similar issue with ORDER_UPDATES and @DynamicUpdate – if so, it hasn't shown up in our unit tests because we never do any updates that change parent-child relationships.

Environment

None

Activity

Show:
Vlad Mihalcea
March 17, 2018, 8:02 AM

You should provide a replicating test case for this issue so we can investigate it.

Roger Dearnaley
May 4, 2018, 5:36 AM

Test case is now attached

Assignee

Unassigned

Reporter

Roger Dearnaley

Fix versions

None

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Worked in

4.3.10

Components

Affects versions

Priority

Major
Configure