简体   繁体   English

休眠一对多SQL执行顺序

[英]Hibernate one-to-many sql execution order

I have two hibernate entities: Order and its Items (one-to-many with save-update cascade, nothing special). 我有两个休眠实体:Order及其Items(一对多,具有保存更新级联,没什么特别的)。

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. 两个用户通过同时添加一个新Item来启动同一Order的更新,这会在两个并发线程中触发Session.saveOrUpdate(order)操作。

Both Order and Item have @Version column to support optimistic lock so this concurrent edit fails with OptimisticLockException as it supposed to be. Order和Item都具有@Version列以支持乐观锁,因此,此并发编辑会因应有的​​OptimisticLockException而失败。

Then I want to increase database consistency and add an unique constraint to the Item (on one of its columns). 然后,我想提高数据库的一致性,并向Item(在其列之一上)添加唯一约束。

Repeating the case above I get constraint violation instead of OptimisticLockException! 重复以上情况,我得到了约束违例而不是OptimisticLockException!

Looks like hibernate does this: 看起来像冬眠这样做:

  • INSERT new item into ITEM table (constraint voilation!) 将新项目插入ITEM表(约束变形!)
  • check optimistic lock 检查乐观锁
  • UPDATE order table UPDATE订单表

Is it possible to force Hibernate to check the optimistic lock BEFORE inserting the child items? 是否可以在插入子项之前强制Hibernate检查乐观锁?

We can catch Optimistic Lock Exception (JPA) or StaleObjectStateException for concurrent updates using versioning and handle the same based on the Use case. 我们可以使用版本控制捕获并发更新的乐观锁异常(JPA)或StaleObjectStateException,并根据用例进行处理。 Either we can reload the latest entity and save it or redirect back for user action. 我们可以重新加载最新的实体并保存它,也可以重定向回以执行用户操作。

It is NOT possible to change INSERT/UPDATE order. 无法更改INSERT / UPDATE顺序。 Hibernate has action queue where INSERT is always before any UPDATE. Hibernate具有操作队列,其中INSERT总是在任何UPDATE之前。

The details are in org.hibernate.engine.spi.ActionQueue.executeActions method. 详细信息在org.hibernate.engine.spi.ActionQueue.executeActions方法中。 The only way to fix the problem above is to remove cascading save: update the parent entity, then add the child items. 解决上述问题的唯一方法是删除级联保存:更新父实体,然后添加子项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM