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

来源:互联网 发布:山东软件外包 编辑:程序博客网 时间:2024/06/17 19:17

最近在搞数据库的并发问题,开发环境用到了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?



2down votefavorite
1

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


0down vote

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);
shareimprove 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?搞不太明白。
0 0
原创粉丝点击