Question

I have two hibernate entities: Order and its Items (one-to-many with save-update cascade, nothing special).

Two users initiate an update of the same Order by adding a new Item at the same time which triggers Session.saveOrUpdate(order) operation in two concurrent threads.

Both Order and Item have @Version column to support optimistic lock so this concurrent edit fails with OptimisticLockException as it supposed to be.

Then I want to increase database consistency and add an unique constraint to the Item (on one of its columns).

Repeating the case above I get constraint violation instead of OptimisticLockException!

Looks like hibernate does this:

  • INSERT new item into ITEM table (constraint voilation!)
  • check optimistic lock
  • UPDATE order table

Is it possible to force Hibernate to check the optimistic lock BEFORE inserting the child items?

Was it helpful?

Solution 2

It is NOT possible to change INSERT/UPDATE order. Hibernate has action queue where INSERT is always before any UPDATE.

The details are in org.hibernate.engine.spi.ActionQueue.executeActions method. The only way to fix the problem above is to remove cascading save: update the parent entity, then add the child items.

OTHER TIPS

We can catch Optimistic Lock Exception (JPA) or StaleObjectStateException for concurrent updates using versioning and handle the same based on the Use case. Either we can reload the latest entity and save it or redirect back for user action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top