title: Hibernate: Enabling useAffectedRows causes OptimisticLockExceptions for no-op updates
body: <p>I need to update a Java app so that SQL updates rely on a count of "affected rows" instead of "found rows" (long story). I ran the app's test suite that uses the MySQL database with <code>useAffectedRows=true</code> and sure enough, there were many failures with this error:</p>
  
  <pre><code>javax.persistence.OptimisticLockException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
  </code></pre>
  
  <p>The actual cause seems to be this exception:</p>
  
  <pre><code>org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
  </code></pre>
  
  <p>As best I can tell, this is only happening when a database object is created and saved to the database in one transaction, then saved again later in a new transaction and no fields have changed (i.e. a no-op). This situation occurs most often with cascading saves. If I refresh the object or change a field value on the object before saving it in the second transaction, everything works fine.</p>
  
  <p>I'm assuming this is happening because enabling <code>useAffectedRows</code> causes those types of updates to return a <code>0</code> for the row count because nothing was actually updated, so Hibernate thinks the update failed.</p>
  
  <p>Is there another setting I need to configure to make Hibernate okay with "no-op updates," or do I need to change how transactions are handled in some way?</p>