1

I use Spring Data JPA with Hibernate as persistence provider over PostgreSQL. I'm trying to provide pessimistic locking:

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);
}

I try to call findOneAndLock from 2 threads. I expect that if Thread A locks object, Thread B should wait until the lock is released. But instead Thread B throws org.springframework.orm.ObjectOptimisticLockingFailureException.

I'm sure that both threads performs select for update (2 such records in database log).

skozlov
  • 384
  • 1
  • 12

1 Answers1

1

The default behavior is to not wait. You need to specify the wait period in the persistence.xml

<properties>
   <property name="javax.persistence.lock.timeout" value="1000"/>
</properties>
Rohit
  • 2,132
  • 1
  • 15
  • 24