如何从Java代码编写乐观和悲观锁定 [英] How to code optimistic and pessimistic locking from java code

查看:93
本文介绍了如何从Java代码编写乐观和悲观锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道什么是乐观锁定和悲观锁定,但是当您编写Java代码时,该怎么做呢?假设我将Oracle与Java一起使用,JDBC中是否有任何方法可以帮助我做到这一点?我将如何配置这个东西?任何指针将不胜感激.

I know what optimistic and pessimistic locking is, but when you write a java code how do you do it? Suppose I am using Oracle with Java, do I have any methods in JDBC that will help me do that? How will I configure this thing? Any pointers will be appreciated.

推荐答案

您可以通过这种方式在数据库表中实现开放式锁定(这是在Hibernate中进行开放式锁定的方式):

You can implement optimistic locks in your DB table in this way (this is how optimistic locking is done in Hibernate):

  1. 在表中添加整数版本"列.
  2. 随着相应行的每次更新,增加此列的值.
  3. 要获取锁定,只需读取该行的版本"值即可.
  4. 将版本=已获得版本"条件添加到的where子句中 您的更新声明.验证更新后受影响的行数. 如果没有受影响的行-有人已经修改了您的条目.
  1. Add integer "version" column to your table.
  2. Increase the value of this column with each update of corresponding row.
  3. To obtain lock, just read "version" value of the row.
  4. Add "version = obtained_version" condition to where clause of your update statement. Verify number of affected rows after update. If no rows were affected - someone has already modified your entry.

您的更新应类似于

UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2

当然,这种机制仅在各方都遵循时才有效,这与DBMS提供的不需要特殊处理的锁相反.

Of course, this mechanism works only if all parties follow it, contrary to DBMS-provided locks that require no special handling.

希望这会有所帮助.

这篇关于如何从Java代码编写乐观和悲观锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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