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).