5

我想将内存中 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 注释时挂起...... :-(

4

2 回答 2

8

两个简单的选择浮现在脑海:

  1. 在保存 newEntity 之前驱逐 oldEntity
  2. 在 oldEntity 上使用 session.merge() 将会话缓存 (newEntity) 中的版本替换为原始 (oldEntity)

编辑:稍微详细一点,这里的问题是 Hibernate 保持一个持久性上下文,这是作为每个会话的一部分被监视的对象。当上下文中有一个附加对象时,您不能对分离的对象(不在上下文中的对象)执行 update() 。这应该有效:

HibernateSession sess = ...;
MyEntity oldEntity = (MyEntity) sess.load(...);
sess.evict(oldEntity); // old is now not in the session's persistence context
MyEntity newEntity = (MyEntity) sess.load(...); // new is the only one in the context now
newEntity.setProperty("new value");
// Evaluate differences
sess.update(newEntity); // saving the one that's in the context anyway = fine

应该这样:

HibernateSession sess = ...;
MyEntity newEntity = (MyEntity) sess.load(...);
newEntity.setProperty("new value");
sess.evict(newEntity); // otherwise load() will return the same object again from the context
MyEntity oldEntity = (MyEntity) sess.load(...); // fresh copy into the context
sess.merge(newEntity); // replaces old in the context with this one
于 2008-10-09T09:42:23.967 回答
0

使用 session.isDirty() 怎么样?JavaDoc 说该方法将回答“如果我们刷新此会话,是否会执行任何 SQL?”这个问题。当然,这只有在你有一个新的干净会话开始时才有效。另一种选择 - 只需使用两个不同的会话。

于 2008-10-08T17:06:13.900 回答