【发布时间】:2019-01-21 13:44:18
【问题描述】:
我正在尝试为我正在处理的行设置一个Lock,直到下一次提交:
entityManager.createQuery("SELECT value from Table where id=:id")
.setParameter("id", "123")
.setLockMode(LockModeType.PESSIMISTIC_WRITE)
.setHint("javax.persistence.lock.timeout", 10000)
.getSingleResult();
我认为应该发生的是,如果两个线程同时尝试写入数据库,一个线程将在另一个之前到达更新操作,第二个线程应该等待 10 秒然后抛出PessimisticLockException。
但是,无论超时设置如何,线程都会挂起,直到另一个线程完成。
看看这个例子:
database.createTransaction(transaction -> {
// Execute the first request to the db, and lock the table
requestAndLock(transaction);
// open another transaction, and execute the second request in
// a different transaction
database.createTransaction(secondTransaction -> {
requestAndLock(secondTransaction);
});
transaction.commit();
});
我预计在第二个请求中,事务将等到超时设置然后抛出PessimisticLockException,但它会永远死锁。
Hibernate 以这种方式生成我对数据库的请求:
SELECT value from Table where id=123 FOR UPDATE
在这个answer 中,我看到Postgres 只允许SELECT FOR UPDATE NO WAIT 将超时设置为0,但不能以这种方式设置超时。
还有其他方法可以与Hibernate / JPA 一起使用吗?
也许以某种方式推荐this way?
【问题讨论】:
标签: java postgresql hibernate jpa