如何使用 JPA 获取 PessimisticLockException

How to get a PessimisticLockException with JPA

我正在尝试 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.