JPA Pessimistic Lock attempt never times out

后端 未结 3 600
悲&欢浪女
悲&欢浪女 2021-01-05 09:34

I\'m trying to use Pessimistic locking in JPA, over Hibernate 3 against a Postgres Database. I can\'t get the lock to time out - it just seems to hang forever.

Here

3条回答
  •  礼貌的吻别
    2021-01-05 10:19

    javax.persistence.lock.timeout doesn't to be working for me either when provided like below

    @QueryHints({@QueryHint(name = "javax.persistence.lock.timeout",value = "15000")})
    

    But then I tried something else which worked. Instead of using @Repository and using CrudRepository, now I am configuring my hbernate using entity manager. Used createQuery along with lock and setting lock timeout. And this configuration is working as expected. I have two transaction running in parellel and trying to lock exact same row in DB. First transaction is able to acquire WRITE lock and holds the lock for around 10 secs before releasing lock. Meanwhile, second transaction tries to acquire lock on same row but since javax.persistence.lock.timeout is set to 15 secs, it waits for lock to be released and then acquires its own lock. Hence making the flow serialized.

    @Component
    public class Repository {
    
        @PersistenceContext
        private EntityManager em;
    
        public Optional getById(int id){
            List list = em.createQuery("select c from Cache c where c.id = ?1")
                                .setParameter(1, id)
                                .setHint("javax.persistence.lock.timeout", 15000)
                                .setLockMode(LockModeType.PESSIMISTIC_WRITE)
                                .getResultList();
    
    
            return Optional.ofNullable(list.get(0));
        }
    
        public void save(Cache cache) {
            cache = em.find(Cache.class, cache.getId());
            em.merge(cache);
        }
    }
    

提交回复
热议问题