title: Trying to save different java objects which represents the same entity. Hibernate
body: <p>(This is a simplification of the real problem)</p>
  
  <p>Let's start with the following little class:</p>
  
  <pre><code>@Entity
  class Test {
          Test(int id, String name) {
              this.id = id;
              this.name = name;
          }
  
          @Id
          private int id;
  
          @Column
          private String name;
  
          @Override
          public int hashCode() {
              return id;
          }
  
          @Override
          public boolean equals(Object obj) {
              if (obj instanceof Test) {
                  return id == ((Test) obj).id;
              }
              return false;
          }
      }
  </code></pre>
  
  <p>If we execute the following, no exception occurs:</p>
  
  <pre><code>EntityManagerFactory factory = Persistence.createEntityManagerFactory("local_h2_persistence");
  EntityManager theManager = factory.createEntityManager();
  EntityTransaction t = theManager.getTransaction();
  
  Test obj1  = new Test(1, "uno");
  
  tA.begin();
  AtheManager.persist(obj1);
  AtheManager.persist(obj1); // &lt;-- No exception
  tA.commit();
  </code></pre>
  
  <p>I guess the second call is ignored, or maybe the object is saved to the DB again. The thing is there is no problem in saving the same entity twice. Now let's try the following:</p>
  
  <pre><code>EntityManagerFactory factory = Persistence.createEntityManagerFactory("local_h2_persistence");
  EntityManager theManager = factory.createEntityManager();
  EntityTransaction t = theManager.getTransaction();
  
  Test obj1  = new Test(1, "uno");
  Test obj1_ = new Test(1, "uno");
  
  tA.begin();
  AtheManager.persist(obj1);
  AtheManager.persist(obj1_); // &lt;-- javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session
  tA.commit();
  </code></pre>
  
  <p>What? How could it possibly be relevant that the object is in a different memory location? Somehow it is and the code throws an exception.</p>
  
  <p>How can I make the second example work just like the first?</p>