如何从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):
- 在表中添加整数版本"列.
- 随着相应行的每次更新,增加此列的值.
- 要获取锁定,只需读取该行的版本"值即可.
- 将版本=已获得版本"条件添加到的where子句中 您的更新声明.验证更新后受影响的行数. 如果没有受影响的行-有人已经修改了您的条目.
- Add integer "version" column to your table.
- Increase the value of this column with each update of corresponding row.
- To obtain lock, just read "version" value of the row.
- 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.
希望这会有所帮助.