title: Can Hibernate work with MySQL's "ON DUPLICATE KEY UPDATE" syntax?
body: <p>MySQL supports an "<code>INSERT ... ON DUPLICATE KEY UPDATE ...</code>" syntax that allows you to "blindly" insert into the database, and fall back to updating the existing record if one exists.</p>
  
  <p>This is helpful when you want quick transaction isolation and the values you want to update to depend on values already in the database.</p>
  
  <p>As a contrived example, let's say you want to count the number of times a story is viewed on a blog. One way to do that with this syntax might be:</p>
  
  <pre><code> INSERT INTO story_count (id, view_count) VALUES (12345, 1)
   ON DUPLICATE KEY UPDATE set view_count = view_count + 1
  </code></pre>
  
  <p>This will be more efficient and more effective than starting a transaction, and handling the inevitable exceptions that occur when new stories hit the front page.</p>
  
  <p>How can we do the same, or accomplish the same goal, with Hibernate?</p>
  
  <p>First, Hibernate's HQL parser will throw an exception because it does not understand the database-specific   keywords. In fact, HQL doesn't like any explicit inserts unless it's an "<code>INSERT ... SELECT ....</code>". </p>
  
  <p>Second, Hibernate limits SQL to selects only. Hibernate will throw an exception if you attempt to call <code>session.createSQLQuery("sql").executeUpdate()</code>.</p>
  
  <p>Third, Hibernate's <code>saveOrUpdate</code> does not fit the bill in this case. Your tests will pass, but then you'll get production failures if you have more than one visitor per second.</p>
  
  <p>Do I really have to subvert Hibernate? </p>