title: How to get generated Identity value from a native JPA INSERT?
body: <p>In my application I'm generating an SQL-INSERT. This insert will be executed as JPA native query (Hibernate) and automatically generate a new identity value in our SQL Server.</p>
  
  <p>How can I receive the generated identity value?</p>
  
  <p>I want to avoid to do a second select to <code>@@IDENTITY</code>, because a second user could have inserted something in the meanwhile, leading to wrong results.
  (seen in <a href="https://stackoverflow.com/questions/13581990/getting-generated-identifier-for-jpa-native-insert-query">Getting generated identifier for JPA native insert query</a> )</p>
  
  <p>The code using @@IDENTITY looks like this:</p>
  
  <pre><code>Query statementInsert = entityManager.createNativeQuery("INSERT INTO x(colum1, column2) VALUES (:value1, :value2)");
  // setting parameters...
  statementInsert.executeUpdate();
  
  Query statmentSelectId = entityManager.createNativeQuery("SELECT @@IDENTITY");
  int generatedId = ((BigDecimal) statmentSelectId.getSingleResult()).intValueExact();
  </code></pre>
  
  <p>I would prefer to put <code>SELECT SCOPE_IDENTITY()</code> right behind my <code>INSERT</code>-Statement (as seen in
  <a href="https://stackoverflow.com/questions/26213292/how-to-get-identity-value-from-sql-server-after-insert-record">How to get Identity value from SQL server after insert record</a>). This would require some kind of "batch execution" for JPA native queries.</p>
  
  <p>I'm dreaming of something like this:</p>
  
  <pre><code>Query statementInsertAndSelectId = entityManager.createNativeQuery("INSERT INTO x(colum1, column2) VALUES (:value1, :value2); SELECT SCOPE_IDENTITY();");
  // setting parameters...
  // ?????????
  int generatedId = ((BigDecimal) statementInsert.getSingleResult()); // not working, JPA complains about "No ResultSet"
  </code></pre>
  
  <p>Using "criteria builder" or "named query" is not possible in my project.</p>