关于hibernate悲观锁设置方法setLockMode无效而setLockOptions有效的解答

本文探讨了在Spring+Hibernate架构下使用MySQL数据库时遇到的悲观锁问题。通过对比LockMode和LockOptions的使用,揭示了在特定条件下LockOptions.UPGRADE才能正确生成带有for update的SQL语句,以实现表级锁定。

最近在搞数据库的并发问题,开发环境用到了spring+hibernate的架构,数据库是mysql,

在用到悲观锁的时候发现用query.setLockMode("u", LockMode.PESSIMISTIC_WRITE);的方式无法锁定表,

打印的sql语句中也没有for update的字段。

后来换成query.setLockOptions(LockOptions.UPGRADE);才成功锁定表。

在百度上查了好久都没有查到原因,后来在一个英文网站找到了答案,原文如下


Should we use LockOptions instead of LockMode in hibernate query?



I see two classes for locking in hibernate -

  1. LockOptions
  2. LockMode

What is the difference between the two? When to use each?


2 Answers



Referring to the Session javadoc http://docs.jboss.org/hibernate/orm/4.2/javadocs/, LockMode parameter should be replaced with LockOptions.

Here is the excerpt from the javadoc.

@Deprecated Object load(String entityName, Serializable id, LockMode lockMode) Deprecated. LockMode parameter should be replaced with LockOptions Return the persistent instance of the given entity class with the given identifier, obtaining the specified lock mode, assuming the instance exists.

Parameters:

entityName - a persistent class

id - a valid identifier of an existing persistent instance of the class

lockMode - the lock level

Returns:

the persistent instance or proxy


I don't have a definite answer but for MySQL the only way to generate a for update sql statement was:

query.setLockOptions(LockOptions.UPGRADE);
share improve this answer
 
 
Are you sure? Or are you talking about this bug? stackoverflow.com/questions/3028478/… –  Reddy  Sep 21 '10 at 16:21
 
Yes, most probably it's the bug you mention. Thanks. –  cherouvim  Sep 21 '10 at 18:03

看来这个似乎是mysql的一个bug?搞不太明白。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值