title: Get inserted Id from NativeQuery Hibernate 5.2+
body: <p>I am using the following code to run native sql queries on hibernate (SQLQuery) has been deprecated. </p>
  
  <pre><code>private static int executeUpdate(String sql) {
      int result = 0;
      Session session = HibernateSessionFactory.getSession();
      org.hibernate.Transaction tr = session.beginTransaction();
      NativeQuery nativeQuery = session.createNativeQuery(sql);
      int executeUpdate = nativeQuery.executeUpdate();
      tr.commit();
      return executeUpdate;
  }
  </code></pre>
  
  <p>It all works fine but I want the same method to also return the id of the last inserted element, I want the way to be table agnostic.</p>
  
  <p>[[EDIT]]</p>
  
  <p>One way to do this can be to pass a native query with <code>returning id</code>
  and then use this code:</p>
  
  <pre><code>private static int executeUpdate(String sql) {
          int result = 0;
          List&lt;HashMap&lt;String, Object&gt;&gt; ret = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;();
          Session session = HibernateSessionFactory.getSession();
          org.hibernate.Transaction tr = session.beginTransaction();
          NativeQuery nativeQuery = session.createNativeQuery(sql);
          ret = nativeQuery.list();
          tr.commit();
          return Integer.parseInt(ret.get(0).get("id").toString());
      }
  </code></pre>
  
  <p>Can there be some other way?</p>