title: Hibernate : Lock a row while update, so user's don't retrieve a counter from it
body: <p>I am working on a Spring-MVC project in which I am using Hibernate as the ORM, PostgreSQL as our DB and in one of our Objects(GroupCanvas), we have a number which is incremented everytime when user takes some action, and then the GroupCanvas object is updated in DB, and it should be unique.</p>
  
  <p>THe problem we have currently is, if multiple users take action in front-end, some of them are getting duplicate numbers. We are working on fixing this now, so later we can implement a sequence and are assured that the numbers are unique.</p>
  
  <p>How can I ensure that when I am updating the row, other users are waiting till the row is updated. I tried LockMode.Pessimistic_write, and a few others, none helped.</p>
  
  <p>Code :</p>
  
  <pre><code>  @Override
      public void incrementNoteCounterForGroupCanvas(int canvasId) {
          Session session = this.sessionFactory.getCurrentSession();
          session.flush();
          Query query = session.createQuery("update GroupCanvas as gc set gc.noteCount=gc.noteCount+1 where gc.mcanvasid=:canvasId");
          query.setParameter("canvasId",canvasId);
          query.executeUpdate();
          session.flush();
      }
  
   @Override
      public GroupCanvas getCanvasById(int mcanvasid) {
          Session session = this.sessionFactory.getCurrentSession();
          session.flush();
          return (GroupCanvas) session.get(GroupCanvas.class, mcanvasid,LockMode.PESSIMISTIC_WRITE);
      }
  </code></pre>
  
  <p>Both methods are in DAO, which has <code>@Transactional</code> annotation, and annotation present in service layer as well. </p>
  
  <p>Thank you. </p>