我正在使用 Criteria API 检索 hibernate 中的对象列表。但是,我需要锁定这些对象,因为同时执行的另一个线程将获取确切的对象,并且在没有悲观锁的情况下只有一个线程会成功。
我尝试如下,但它不起作用。
List esns = session
.createCriteria(Reddy_Pool.class)
.add(Restrictions.eq("status", "AVAILABLE"))
.add(Restrictions.eq("name", "REDDY2"))
.addOrder(Order.asc("id"))
.setMaxResults(n)
.setLockMode(LockMode.PESSIMISTIC_WRITE) //not working at all
.list();
Update:我在此语句后执行更新,以便我希望两个线程读取不同的行,或者至少第二个线程应该等待,直到第一个线程完成事务并离开锁。
hibernate 生成的查询如下。
Hibernate: select this_.id as id1_0_, this_.name as name1_0_,
this_.orderitem_id as orderitem3_1_0_, this_.status as status1_0_,
this_.store as store1_0_, this_.vendor as vendor1_0_, this_.version as version1_0_
from reddy_pool this_
where this_.status=? and and this_.name=? order by this_.id asc limit ?
Update:正如 Pascal Thivent(非常感谢 Pascal)提到的那样,这似乎是 3.5.2 版本中的一个错误,我已作为会员加入并关注该问题。希望它将包含在下一个版本中。
不过我尝试在这里使用另一种方法session.buildLockRequest()
...但我不太清楚如何使用它,并且使用下面的代码根本没有任何效果。
for (int i=0; i < n; i++)
session.buildLockRequest(LockOptions.UPGRADE).lock(esns.get(i));