I want to compare the current value of the sleeping entity in memory with the value in the database:
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
sess.update(newEntity);
In CODEBLOCK # 1, I get this newEntity.getProperty()="new value"AND oldEntity.getProperty()="new value"(although I expected oldEntity.getProperty()="old value", of course). In fact, both objects in memory are the same.
I mixed up with HibernateSessionFactory.getSession().evict(newEntity)and tried to install oldEntity=nullin order to get rid of it (I need this just for comparison):
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
oldEntity = null;
sess.update(newEntity);
and now these two objects are different, but of course I get scary org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session.
Any idea?
EDIT: I tried a dual session strategy; I changed mine HibernateSessionFactoryto implement a session map, and then ...
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());
HibernateSessionFactory.closeSession(SessionKeys.ALTERNATE);
My unit test freezes when I try to print the note oldEntity ...: - (