title: JPA with MySQL returning wrong last inserted id
body: <p>I'm using JPA for creating a new entity in a stateless bean, "hg" table is a MySQL InnoDB with autoincrement ID column as a primary key:</p>
  
  <pre><code>[...]
  // if we haven't an ID, it's a new hg
  if (hg.getIdHg() == null) {
    hg.setDate(new Date());
    hg.setIdCli(cli);
  }
  // fill fields
  hg.setIdOp(op);
  [...]
  hg.setText(text);
  // add hg to cli
  if (!cli.getHgCollection().contains(hg)) {
    Cli.getHgCollection().add(hg);
  }
  //
  jpa.persist(hg);
  jpa.flush();
  //
  LOG.info("*** hg stored with id " + hg.getIdHg());
  [...]
  </code></pre>
  
  <p>In the Hg entity id column is defined in this way:</p>
  
  <pre><code>@Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "id_hg")
  private Integer idHg;
  </code></pre>
  
  <p>It almost works, but in 3 years I've had 6 cases where hg.getIdHg() is wrong, ie: inserted record has id 2809643 but hg.getIdHg() returns 2809638!</p>
  
  <p>Theres nothing between persist, flush and the LOG line, no strange code before or after, so I don't understand why I'm getting an older ID.</p>
  
  <p>I've googled of course but I didn't fine anything useful, I'm thinking about changing the table structure, stripping the autogenerated ID and adding a calculated column, but it involves a lof of changes so I prefer to find a way to solve this.</p>
  
  <p>EDIT: I'm using glassfish 4.1, JPA provider is EclipseLink (JPA 2.1)</p>