title: Hibernate: comparing current & previous record
body: <p>I want to compare the current value of an in-memory Hibernate entity with the value in the database:</p>
  
  <pre><code>HibernateSession sess = HibernateSessionFactory.getSession();
  MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
  newEntity.setProperty("new value");
  MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
  // CODEBLOCK#1 evaluate differences between newEntity and oldEntity
  sess.update(newEntity);    
  </code></pre>
  
  <p>In <strong>CODEBLOCK#1</strong> I get that <code>newEntity.getProperty()="new value"</code> AND <code>oldEntity.getProperty()="new value"</code> (while I expected <code>oldEntity.getProperty()="old value"</code>, of course). In fact the two objects are exactly the same in memory.</p>
  
  <p>I messed around with <code>HibernateSessionFactory.getSession().evict(newEntity)</code> and attempted to set <code>oldEntity=null</code> to get rid of it (I need it only for the comparison):</p>
  
  <pre><code>HibernateSession sess = HibernateSessionFactory.getSession();
  MyEntity newEntity = (MyEntity)sess.load(MyEntity.class, id);
  newEntity.setProperty("new value");
  HibernateSessionFactory.getSession().evict(newEntity);
  MyEntity oldEntity = (MyEntity)sess.load(MyEntity.class, id);
  // CODEBLOCK#1 evaluate differences between newEntity and oldEntity
  oldEntity = null;
  sess.update(newEntity);
  </code></pre>
  
  <p>and now the two entities are distinct, but of course I get the dreaded <code>org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session</code>.</p>
  
  <p>Any idea?</p>
  
  <p><strong>EDIT:</strong> I tried the double session strategy; I modified my <code>HibernateSessionFactory</code> to implement a map of session and then...</p>
  
  <pre><code>Session session1 = HibernateSessionFactory.getSession(SessionKeys.DEFAULT);
  Session session2 = HibernateSessionFactory.getSession(SessionKeys.ALTERNATE);
  Entity newEntity = (Entity)entity;
  newEntity.setNote("edited note");
  Entity oldEntity = (Entity)session1.load(Entity.class, id);
  
  System.out.println("NEW:" + newEntity.getNote());
  System.out.println("OLD: " + oldEntity.getNote()); // HANGS HERE!!!
  
  HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE);
  </code></pre>
  
  <p>My unit test hangs while attempting to print the oldEntity note... :-(</p>