java - 如何使用 JPA 获取 PessimisticLockException

标签 java jpa locking jpa-2.0 pessimistic-locking

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

相关文章:

java - 单击 JFrame 中的 JButton 时如何更改现有图像? ( java )

java - jboss 下的多个数据库可供读取

java - 将 Spring 3.1 与 Hibernate 4.0.1 一起使用时,如何解决 java.lang.ClassNotFoundException : org. hibernate.util.DTDEntityResolver?

mysql - MySQL InnoDB 表的恒定锁等待超时

Java Swing BorderLayout resize困难

java - com.mysql.jdbc.Driver 做什么?

java - ReentrantLock -> lockInterruptically() 有时不会检查中断状态?

c# - 如果我在写入变量时锁定,如果读取是原子的,我是否也需要在读取时锁定?

java - 使用 Java 进行 RPC 和 UniData 模拟

json - 使用 Jackson 将 JPA 实体序列化为 JSON