我想将内存中 Hibernate 实体的当前值与数据库中的值进行比较:
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);
在CODEBLOCK#1中,我得到了newEntity.getProperty()="new value"
AND oldEntity.getProperty()="new value"
(当然,我期望oldEntity.getProperty()="old value"
的是)。实际上这两个对象在内存中是完全一样的。
我搞砸了HibernateSessionFactory.getSession().evict(newEntity)
并试图oldEntity=null
摆脱它(我只需要它来进行比较):
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);
现在这两个实体是不同的,但我当然会感到恐惧org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
。
任何的想法?
编辑:我尝试了双会话策略;我修改了我HibernateSessionFactory
以实现会话地图,然后......
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);
我的单元测试在尝试打印 oldEntity 注释时挂起...... :-(