当前位置:  开发笔记 > 编程语言 > 正文

Hibernate:比较当前和以前的记录

如何解决《Hibernate:比较当前和以前的记录》经验,为你挑选了1个好方法。

我想比较内存中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笔记时,我的单元测试挂起...... :-(



1> Cowan..:

我想到了两个简单的选择:

    在保存newEntity之前逐出oldEntity

    在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

推荐阅读
我我檬檬我我186
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有