title: Hibernate JPA persistence - How to obtain new entity identifier after insert / save / merge
body: <p>I am quite new to Hibernate / JPA persistence and am trying to find how to obtain the ID of an inserted record in the database via the new object I create to do so.</p>
  
  <p>I am using Hibernate 4.0.4 and am utilising hibernates session API as opposed to the EntityManager.</p>
  
  <h2>User class</h2>
  
  <pre><code>@Entity
  @Table(name = "users")
  public class User implements Serializable {
  
      private String email;
      private String firstName;
      private int id;
      private String lastName;
      private String password;
  
      @Column(name = "email", nullable = false, unique = true)
      public String getEmail() {
          return email;
      }
  
      @Column(name = "firstName", nullable = false)
      public String getFirstName() {
          return firstName;
      }
  
      @Id
      @Column(name = "id")
      public int getId() {
          return id;
      }
  
      @Column(name = "lastName")
      public String getLastName() {
          return lastName;
      }
  
      @Column(name = "password", nullable = false)
      public String getPassword() {
          return password;
      }
  
      public void setEmail(String email) {
          this.email = email;
      }
  
      public void setFirstName(String firstName) {
          this.firstName = firstName;
      }
  
      public void setHeroes(List&lt;Hero&gt; heroes) {
          this.heroes = heroes;
      }
  
      public void setId(int id) {
          this.id = id;
      }
  
      public void setLastName(String lastName) {
          this.lastName = lastName;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
  }
  </code></pre>
  
  <h2>Execution code - attempt 1</h2>
  
  <pre><code>User user = new User();
  user.setEmail((String) arg.get("email"));
  user.setFirstName((String) arg.get("firstName"));
  user.setLastName((String) arg.get("lastName"));
  user.setPassword(Password.getSaltedHash((String) arg.get("password")));
  Transaction tx = sessionFactory.getCurrentSession().beginTransaction(); //committed later on...
  int id = (Integer) sessionFactory.getCurrentSession().save(user); //This always returns 0 even though inserted rows in database have IDs as expected
  </code></pre>
  
  <h2>Execution code - attempt 2</h2>
  
  <pre><code>//Same as before for defining user...
  
  Transaction tx = sessionFactory.getCurrentSession().beginTransaction(); //commited later on...
  user = (User) sessionFactory.getCurrentSession().merge(user);
  int id = user.getId(); //This also always returns 0 even though the rows are being inserted into the database as expected
  </code></pre>
  
  <p>So my question is:</p>
  
  <p>How can I successfully persist the user object to the database and obtain the ID of the record through that user object?</p>