如何使用并发用户处理乐观锁定项目数量更新?

问题描述 投票:0回答:1

我有更新项目数量的方法。

实体具有@Version注释版本属性。

有一个项目列表端点/items还有一个项目更新端点/item/update(考虑作为产品库存,购买项目)

所以N个并发用户想要更新相同的项目。

但有抛出org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1那个例外。在更新时。

而且在这个时候,/items端点无法返回数据。或者等待用户以太多的延迟返回。(如果此时更新用户数量太多,它也会获得exception timeout)。

那么如何处理这种情况而不会遗漏? (可以很好的实施)

java spring hibernate transactional optimistic-locking
1个回答
0
投票

不幸的是,当存在争用时,JPA / Hibernate对批量插入的效果不佳:每当在Hibernate会话的上下文中抛出任何异常时,你就不幸了。

见13.2.3。异常处理:https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch13.html#transactions-optimistic

特别:

Hibernate抛出的异常都不能被视为可恢复的。确保通过在finally块中调用close()来关闭Session。

在过去,我不得不将JPA代码迁移到QueryDSL或者回退到原始SQL和JdbcTemplate(类似于How to do multiple inserts in database using spring JDBC Template batch?)。

© www.soinside.com 2019 - 2024. All rights reserved.