表级别在Hibernate中锁定 [英] Table level Lock in Hibernate

查看:601
本文介绍了表级别在Hibernate中锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Hibernate版本4.我们在批处理过程中有一个问题。我们的系统如下所示


  1. 选择处于PENDING状态的记录集

  2. 更新立即处于IN PROGRESS状态

  3. 处理并更新为COMPLETED状态



<当我们有两个服务器并且同时执行时,我们担心会出现并发问题。所以我们想要实现DB Lock的前两个步骤。我们使用 query.setLockOptions(),但似乎不工作。是否有其他任何其他有表级锁或行级锁,直到它完成选择和更新。两者都在同一个会话中。



我们在JDBC中有 LOCK TABLE< TABLE_NAME& WRITE 。但是我们如何在hibernate中实现或者可以在hibernate中实现select..for update?

解决方案

。for update在Hibernate中通过 LockMode支持。 UPGRADE ,您可以在其中设置,例如, NamedQuery



但使用应用程序/手动表行锁定有几个缺点(特别是当一个数据库连接中断一个事务),你的update-procedure可以没有它:





  • 更新表集状态='PENDING',server_id = 1其中state ='IN PROGRESS';

  • 提交事务

  • 从表格中选择state ='PENDING'和server_id = 1;

  • [process records]



    • 每个服务器必须有一个唯一的号码才能工作,但它不太容易出错,你让DBMS做它应该是什么好:isolation请参阅 ACID )。


      I use Hibernate version 4. We have a problem in batch process. Our system works as below

      1. Select set of records which are in 'PENDING' state
      2. Update immediately to 'IN PROGRESS' state
      3. Process it and update to 'COMPLETED' state

      The problem when we have two servers and executing at same time, we fear of having concurrency issue. So we would like to implement DB Lock for first two steps. We used query.setLockOptions(), but it seems not working. Is there any other to have table level lock or Row level lock till it completes select and update. Both are in same session.

      We have options in JDBC that LOCK TABLE <TABLE_NAME> WRITE. But how do we implement in hibernate or is it possible to implement select..for update in hibernate?

      解决方案

      "Select ... for update" is supported in Hibernate via LockMode.UPGRADE which you can set in, for example, a NamedQuery.

      But using application/manual table-row locking has several drawbacks (especially when a database connection gets broken half-way a transaction) and your update-procedure can do without it:

      • Start transaction.
      • update table set state='PENDING', server_id=1 where state='IN PROGRESS';
      • Commit transaction
      • select from table where state='PENDING' and server_id=1;
      • [process records]

      Each server must have a unique number for this to work, but it will be less error-prone and you let the DBMS do what it is supposed to be good at: isolation (see ACID).

      这篇关于表级别在Hibernate中锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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