title: Hibernate JPA - PESSIMISTIC.WRITE not working
body: <p>I'm using the Hibernate implementation of JPA 2.0 to create a counter in a table row.  I'm using MySQL 5.5 with the InnoDB engine.   I am trying to lock the counter row so that no processes outside the JVM can view that counter until my code has incremented it.   My code looks like this:</p>
  
  <pre><code>  //inside a Transaction....
  
    //key is an enum
    final PropertyKey key = PropertyKey.DEPLOY_COUNTER;
    final Query query =
       entityManager.createQuery("FROM Property s where propertyKey = :key").setParameter("key", key);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    LOG.debug("Blocking (maybe) while waiting to update deploy counter");
    final Property counterAsProperty = (Property) query.getSingleResult();
  
    try
    {
       Thread.sleep(15000);
       //while sleeping I use MySQL cli to check value of property in database
    }
    catch (InterruptedException e)
    {
       e.printStackTrace();
    }
  
    //in java, increment counter by one and then save in db
    //...
  </code></pre>
  
  <p>I use Thread.sleep() to pause the code in the middle of the transaction.  While the thread is sleeping, I use the MySQL CLI client to log into the database and check the value of the property. That session looks something like this:</p>
  
  <pre><code>user@mypc [user]&gt; begin work;
  Query OK, 0 rows affected (0.00 sec)
  
  user@mypc [user]&gt; select * from property where property_key = 'DEPLOY_COUNTER';
  +----+---------+-----------+--------------------+----------------+
  | id | version | encrypted | property_key       | property_value |
  +----+---------+-----------+--------------------+----------------+
  | 10 |       0 |         0 | DEPLOY_COUNTER     | 66             |   
  +----+---------+-----------+--------------------+----------------+
  </code></pre>
  
  <p>Notice how the query returns immediately(0.00 sec) when I expected it to block until the thread had quit sleeping and the transaction completed.   My understanding of LockModeType.PESSIMISTIC_WRITE is that it should put the retrieved row in an exclusive lock, unavailable for reading or writing by another transaction.</p>
  
  <p>NOTE:  updates to this row do block while the thread is sleeping.</p>
  
  <p>Why can another DB connection view the data when the other transaction is running if I've set PESSIMISTIC_WRITE lock mode?</p>