While trying to migrate from Hibernate 5.0.12 to a newer version (in this case 5.2.18) I observed a change in behaviour for multi-table entities (e.g. mapping with join table for some attributes), which can lead to StaleStateExceptions since 5.2.15. Older versions like 5.2.14 or 5.0.12 do not fail but succeed.
I will attach a failing test case for 5.2.18, but it also fails for recent 5.3.x and 5.4.x versions, when you change the Hibernate version in the POM file.
The test case does not fail for version 5.2.14 and 5.0.12, for example.
So, I think this regression could possibly be introduced in version 5.2.15, in particular perhaps by issues HHH-2558/HHH-5797.
Updates to joined tables couldn't be batched in older versions, but HHH-2558/HHH-5797 introduced changes in this regard.
Hibernate 5.0.12 generates this code in the test case:
The update to the company_tax table will fail, but then an insert will be generated.
Hibernate 5..2.18 generates this code in the test case:
Here, the update to the company_tax table is batched and fails with an StaleStateException; an insert is not tried anymore, thus failing the test case.
, please take a look at this...
This looks like a problem when Session#saveOrUpdate is used to update an entity value mapped to the joined table, and there is currently no row for that entity in the joined table yet. The exception gets thrown when the ```Session``` gets flushed.
A workaround is to use Session#merge instead of Session#saveOrUpdate.