title: Hibernate PESSIMISTIC_WRITE not locking db and returning oldValue
body: <p>I am using "Postgres" database and pessimistic_locking for locking database row.</p>
  
  <p>I have the following code</p>
  
  <pre><code>@Transactional
  doProcess(int id, int quantity){
     Article article = lockArticle(id);
     modifyArticle(article, quantity);
  }
  </code></pre>
  
  <p>This is lockArticle() function which locks and fetches article from DB(Postgres)</p>
  
  <pre><code>Article lockArticle(int id){
          return sessionFactory.getCurrentSession().createCriteria(Article.class)
                  .add(Restrictions.eq("id", id))
                  .setLockMode(LockMode.PESSIMISTIC_WRITE)
                  .setTimeout(10000)
                  .getUniqueResult();
      }
  </code></pre>
  
  <p>Here is the modifyArticle(), which basically deletes/updates article entry in database.</p>
  
  <pre><code>modifyArticle(Article article, int quantity){
  
   if(article.getQuantity()&lt;quantity){
       dao.delete(article);
   }
  
   else{
     article.setQuantity(article.getQuantity()-quantity)
     dao.updateArticle(article);
    }
  }
  </code></pre>
  
  <p>//DAO for updateArticle</p>
  
  <pre><code>@Transactional
  updateArticle(Article article){
     sessionFactory.getCurrentSession().saveOrUpdate(article);
  }
  </code></pre>
  
  <p>Let's say initially in db, article has quantity 10. </p>
  
  <p>I have spawned 2 threads to update article quantity, first thread is spawned with quantity = 2, second thread with 3. So ideally the DB after both the finished processing should be 5(10-2-3).</p>
  
  <p>But database net quantity in db is either 8(10-2)/7(10-3). </p>
  
  <p>Can someone please help me understand why PESSIMISTIC_LOCKING is not working and what would be a workaround to fix this?</p>