title: How to get Id of last persisted entity using JPA
body: <p>I am looking a smart and easily readable way to get the id of a persisted entity using <code>JPA</code>. The id is an <code>Integer</code>.</p>
  
  <p>One could think of the following solutions:</p>
  
  <ol>
  <li>Without using <code>GeneratedValue</code> strategy. This requires looking for a free id before persisting, then putting it into the entity to be persisted: cumbersome, but works.</li>
  <li>With a <code>GeneratedValue</code> strategy. The persistence provider will take care of the id generation. This looks smarter, but how to get the id? </li>
  </ol>
  
  <p>See below for solution 2</p>
  
  <pre><code>MyEntity en = new MyEntity();
  en.setName("My name");
  em.persist(en);
  System.out.println(en.getId());
  </code></pre>
  
  <p>This prints a null id! </p>
  
  <p>Any suggestions? I am using MySql, EclipseLink, but need a portable solution.</p>