title: How to use the Hibernate optimistic locking version property on the front end?
body: <p>Optimistic locking using the version attribute for an entity works fine and is easy to implement:</p>
  
  <pre><code>&lt;version property="VERSION" type="int" column="EX_VERSION" /&gt;
  </code></pre>
  
  <p>The entity has a property of the following type:</p>
  
  <pre><code>private int VERSION;
  public int getVERSION() { return VERSION; }
  public void setVERSION(int VERSION) { this.VERSION = VERSION; }
  </code></pre>
  
  <p>So far, so good. Now service methods return a data transfer object (DTO) for the entity above, which the views display in HTML. For update pages, the VERSION attribute is stored in an HTML hidden field and submitted with the form.</p>
  
  <p>The intent is to use the version property to ensure that a user's update will fail if the information displayed is accompanied by an old version.</p>
  
  <p>The controller responds to a users update request by invoking a service method with the DTO containing the updated information (including the version property), and the service method in turn uses a data access object (DAO) to persist the changes:</p>
  
  <pre><code>public void update(SimpleDTO dto) {
      SimplyEntity entity = getSimpleDao().load(dto.getId());
      copyProperties(dto, entity); // all properties, including VERSION copied to entity
      getSimpleDao().update(entity);
  }
  </code></pre>
  
  <p>The problem is that the version property copied into the entity by copyProperties(...) is not respected by Hibernate. I tracked down the reason in the following forum: <a href="https://forum.hibernate.org/viewtopic.php?f=1&amp;t=955893&amp;p=2418068" rel="noreferrer">https://forum.hibernate.org/viewtopic.php?f=1&amp;t=955893&amp;p=2418068</a></p>
  
  <p>In short, when load() is called, Hibernate caches the version property in the session cache and it doesn't matter what it's value is subsequently changed to. I agree that this is the correct behavior, but I have been instructed by Bosses to pass the version via an HTML form property (if there is a better pattern for this, I'd love to hear it).</p>
  
  <p>One solution I am exploring now is to evict the entity from the session after it's version has been set using hibernateTemplate.evict(simpleEntity) before the update happens. I hope this works, but it doesn't seem efficient.</p>
  
  <p>I would like to ask Hibernate to check the version property on the instance itself, rather than only from the session cache.</p>
  
  <p>Thanks in advance for answers!</p>
  
  <p>--
  LES</p>