JPA和乐观锁定模式 [英] JPA and optimistic locking modes

查看:98
本文介绍了JPA和乐观锁定模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Oracle博客上阅读了一篇文章,其中此处关于JPA和锁定模式

I read an article on the blog of Oracle here about JPA and locking modes.

我不完全了解OPTIMISTICOPTIMISTIC_FORCE_INCREMENT锁定模式类型之间的区别.

I don't entirely understand the difference between OPTIMISTIC and OPTIMISTIC_FORCE_INCREMENT lock mode types.

OPTIMISTIC模式:

当用户使用此模式锁定实体时,将在事务开始时对版本字段实体(@version)进行检查,并在事务结束时对版本字段进行检查.如果版本不同,则事务回滚.

When a user locks an entity with this mode, a check is done on the version field entity (@version) at the beginning of transaction and a check on the version field is also done at the end of the transaction. If versions are different, the transaction rolls back.

OPTIMISTIC_FORCE_INCREMENT模式:

当用户选择此模式时,他必须将EntityManager的状态flush()到数据库中以手动增加版本字段.因此,所有其他乐观交易将失效(回滚).在事务结束时也会进行版本检查,以提交或回滚事务.

When a user chooses this mode, he has to flush() the state of EntityManager into database to increment the version field manually. Thus, all other optimistic transactions will be invalidated (roll back). A check on the version is also done at end of transaction to commit or roll back transaction.

似乎很清楚,但是我什么时候应该使用OPTIMISTICOPTIMISTIC_FORCE_INCREMENT模式呢?我看到的唯一标准是,当我希望事务优先于其他事务时应用OPTIMISTIC_FORCE_INCREMENT模式,因为选择此模式将回滚所有其他正在运行的事务(如果我理解机制很清楚).

It seems clear but when should I use OPTIMISTIC versus OPTIMISTIC_FORCE_INCREMENT modes ? The only criteria that I see is to apply OPTIMISTIC_FORCE_INCREMENT mode when I want the transaction to have precedence over the others because choosing this mode will roll back all other running transactions (if I understand well mecanism).

还有其他原因选择此模式而不是OPTIMISTIC模式吗?

Is there other reason to choose this mode rather than OPTIMISTIC mode?

谢谢

推荐答案

通常,您永远不会使用lock()API进行乐观锁定. JPA会自动检查任何更新或删除的任何版本列.

Normally you would never use the lock() API for optimistic locking. JPA will automatically check any version columns on any update or delete.

lock()API用于乐观锁定的唯一目的是当您的更新依赖于另一个未更改/更新的对象时.如果其他对象发生更改,这将使您的事务仍然失败.

The only purpose of the lock() API for optimistic locking is when your update depends on another object that is not changed/updated. This allows your transaction to still fail if the other object changes.

何时执行此操作取决于应用程序和用例. OPTIMISTIC将确保在提交时未更新另一个对象. OPTIMISTIC_FORCE_INCREMENT将确保另一个对象尚未更新,并在提交时增加其版本.

When to do this depends on the application and the use case. OPTIMISTIC will ensure the other object has not been updated at the time of your commit. OPTIMISTIC_FORCE_INCREMENT will ensure the other object has not been updated, and will increment its version on commit.

乐观锁定始终在提交时进行验证,并且在提交之前无法保证成功.您可以使用flush()提前强制数据库锁定,或触发更早的错误.

Optimistic locking is always verified on commit, and there is no guarantee of success until commit. You can use flush() to force the database locks ahead of time, or trigger an earlier error.

这篇关于JPA和乐观锁定模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆