我使用JPA 2.0的Hibernate實現在表格行中創建一個計數器。我正在使用InnoDB引擎的MySQL 5.5。我試圖鎖定計數器行,以便JVM之外的任何進程都不能查看該計數器,直到我的代碼增加它爲止。我的代碼如下所示:休眠JPA - PESSIMISTIC.WRITE不工作
//inside a Transaction....
//key is an enum
final PropertyKey key = PropertyKey.DEPLOY_COUNTER;
final Query query =
entityManager.createQuery("FROM Property s where propertyKey = :key").setParameter("key", key);
query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
LOG.debug("Blocking (maybe) while waiting to update deploy counter");
final Property counterAsProperty = (Property) query.getSingleResult();
try
{
Thread.sleep(15000);
//while sleeping I use MySQL cli to check value of property in database
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//in java, increment counter by one and then save in db
//...
我使用Thread.sleep()來暫停事務中間的代碼。當線程處於睡眠狀態時,我使用MySQL CLI客戶端登錄數據庫並檢查屬性的值。這會看起來是這樣的:
[email protected] [user]> begin work;
Query OK, 0 rows affected (0.00 sec)
[email protected] [user]> select * from property where property_key = 'DEPLOY_COUNTER';
+----+---------+-----------+--------------------+----------------+
| id | version | encrypted | property_key | property_value |
+----+---------+-----------+--------------------+----------------+
| 10 | 0 | 0 | DEPLOY_COUNTER | 66 |
+----+---------+-----------+--------------------+----------------+
注意如何查詢立即返回(0.00秒)時,我預期它阻止,直到線程已經退出睡眠和交易完成。我對LockModeType.PESSIMISTIC_WRITE的理解是,它應該將檢索到的行放入獨佔鎖中,不可用於其他事務的讀取或寫入。
注意:當線程正在休眠時,此行的更新會阻塞。
如果我設置了PESSIMISTIC_WRITE鎖定模式,爲什麼另一個數據庫連接可以在另一個事務正在運行時查看數據?