Table level Lock in Hibernate

心已入冬 提交于 2019-12-12 02:46:38

问题


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?


回答1:


"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).



来源:https://stackoverflow.com/questions/23720103/table-level-lock-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!