title: How expensive is committing a hibernate transaction?
body: <p>I have a the following use case where I'm receiving a message via JMS regarding an entity, via a unique property of it (not PK) and it requires me to update the state of the entity:  </p>
  
  <pre><code>HibernateUtil.beginSession();  
  HibernateUtil.beginTransaction();  
  try{  
    Entity entity = dao.getEntityByUniqueProperty(propertyValue);  
    if (entity==null){  
      entity = dao.addEntityByUniqueProperty(propertyValue)  
    }  
    entity.setSomeProperty(otherPropertyValue);
    HibernateUtil.commitTransaction();
  } catch (ConstraintViolationException e){  
    HibernateUtil.rollbackTransaction();  
    //Do other things additionally  
  } catch (StaleStateObjectException e){  
    HibernateUtil.rollbackTransaction();  
    //Do other things additionally  
  } finally {  
    HibernateUtil.closeSession();  
  }
  </code></pre>
  
  <p>In this use case I have to be prepared for the fact that the entity which I'm trying to update is not yet created and so I request that such entity be created (a template of it to be precise with the unique property) and then I change it.
  My dillema is as follows:
  On the one hand I have two clearly different blocks and I should use the different catch clauses where appropriate BUT seeing as the end case where the entity is not there when I query but is there a ms later when I try to create it (hence ConstraintViolationException) is something that shouldn't happen too often and to insert because of that an additional commit/beginTransaction at the middle just seems waistfull.  </p>
  
  <p>I'm mainly concerned about the additional performance hit of the session synchronization and the JDBC connection which are done when the commit/begin occur.<br>
  Am I wrong? Am I looking for optimization where I shouldn't? Am I missing something?<br>
  Thanks in advance</p>