我正在使用 Criteria API 检索休眠中的对象列表。但是,我需要锁定这些对象,因为同时执行的另一个线程将获得确切的对象,并且只有一个线程会在没有悲观锁定的情况下成功。
我尝试如下,但它不工作。
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();
更新:我在这个语句之后执行更新,所以我希望两个线程都读取不同的行,或者至少第二个线程应该等到第一个线程完成事务并离开锁。
下面是休眠生成的查询。
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 ?
更新:Pascal Thivent(非常感谢 Pascal)提到的 3.5.2 版本中似乎存在一个错误,我已作为会员加入并关注该问题。希望它会包含在下一个版本中。
但是,我尝试在这里使用另一种方法session.buildLockRequest()
... 但我不太清楚如何使用它,并且使用下面的代码根本没有任何效果。
for (int i=0; i < n; i++)
session.buildLockRequest(LockOptions.UPGRADE).lock(esns.get(i));