使用ObjectOptimisticLockingFailureException,悲观锁定失败

时间:2015-05-28 13:58:49

标签: java spring hibernate postgresql jpa

我使用Spring Data JPA和Hibernate作为PostgreSQL的持久性提供程序。我试图提供悲观锁定:

public interface MediaRepository extends JpaRepository<Media, Long>, MediaRepositoryCustom {
Long countByCreatedBy(User creator);

@Query("select m from Media m where m.id = ?1")
@Lock(LockModeType.PESSIMISTIC_WRITE)
Media findOneAndLock(Long id);
}

我尝试从2个线程中调用findOneAndLock。我希望如果Thread A锁定对象,Thread B应该等到锁被释放。但是Thread B会引发org.springframework.orm.ObjectOptimisticLockingFailureException

我确信两个线程都执行select for update(数据库日志中有2个这样的记录)。

1 个答案:

答案 0 :(得分:1)

默认行为是不等待。您需要在persistence.xml

中指定等待期
<properties>
   <property name="javax.persistence.lock.timeout" value="1000"/>
</properties>
相关问题