如何使用Criteria API指定悲观锁定?

时间:2010-06-12 11:24:32

标签: hibernate hibernate-criteria

我正在使用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();

更新:我在此语句之后执行更新,因此我希望两个线程都读取不同的行,或者至少第二个线程应该等到第一个线程完成事务并离开锁定

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 ?

更新:这似乎是3.5.2版本中的一个错误,因为Pascal Thivent(非常感谢Pascal)提及,我已加入成员并观看此问题。希望它将包含在下一个版本中。

然而,我尝试使用另一种方法session.buildLockRequest() ...但我无法弄清楚如何使用它,使用下面的代码根本没有任何效果。

for (int i=0; i < n; i++)
    session.buildLockRequest(LockOptions.UPGRADE).lock(esns.get(i));

1 个答案:

答案 0 :(得分:3)

您使用的是什么版本的Hibernate?这可能是HHH-5275吗?您确定没有生成FOR UPDATE语句吗?你能展示生成的SQL吗?

相关问题