我正在尝试 JPA 对数据库锁定的支持,以避免记录中的并发请求。在我的场景中,我需要使用悲观锁。我使用以下方法得到了这一点:
EntityManager em;
...
Map<String,Object> props = new HashMap<String,Object>();
props.put("javax.persistence.lock.timeout", 0);
em.find(MyEntity.class, id, LockModeType.PESSIMISTIC_READ, props)
但通过这种方法,我处理的是 LockTimeoutException
而不是 PessimisticLockException
。 如何具体处理PessimisticLockException
?
最佳答案
根据规范,PessimisticLockException
仅发生在事务级回滚时:
When the lock cannot be obtained, and the database locking failure results in transaction-level rollback, the provider must throw the PessimisticLockException and ensure that the JTA transaction or EntityTransaction has been marked for rollback.
您的事务似乎仅包含单个数据检索查询,并且持久性提供程序认为如果该查询上发生锁定错误,则回滚将被视为语句级回滚。根据规范,这将导致 LockTimeoutException
:
When the lock cannot be obtained, and the database locking failure results in only statement-level rollback, the provider must throw the LockTimeoutException (and must not mark the transaction for rollback).
我认为这是驱动程序/持久性提供程序的一种聪明方法,它让您有机会重复/修复您的语句,而不是隐式回滚整个事务。
一般来说,我认为如果您在查找之前进行了插入或更新(或一些更复杂的数据操作语句),那么您将得到PessimisticLockException
。
关于java - 如何使用 JPA 获取 PessimisticLockException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309045/