休眠:安全地将对象重新连接到会话 [英] Hibernate: Safely reattach an object to the session

查看:73
本文介绍了休眠:安全地将对象重新连接到会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过在地图中存储(可能分离的)对象,我在整个hibernate会话中维护对象的缓存。当缓存命中时,我测试对象是否已经是 Session.contains(object)的会话的一部分。如果没有,我用 Session.lock(object,LockMode.NONE)重新附加它。



问题是,如果先前在会话中加载了相同的对象,则会引发org.hibernate.NonUniqueObjectException。给定一个分离的实例,我无法预先知道是否会抛出异常,而不会触及数据库。



有几个解决方法:


  1. 在开始时重新附加所有缓存的对象的每笔交易。
  2. 捕获NonUniqueObjectException,然后调用session.load(object.class,object.getId());

这些都不像提前为对象类+ id检查会话那样干净。

有没有办法做到这一点?

解决方案

Session.merge()应该这样做:

  obj = session.merge(obj); 


I'm maintaining a cache of objects across hibernate sessions by storing (possibly-detached) objects in a map. When the cache gets a hit, I test if the object is already part of the session with Session.contains(object). If not, I re-attach it with Session.lock(object, LockMode.NONE).

The problem is, if the same object was loaded previously in the session, it throws a org.hibernate.NonUniqueObjectException. Given a detached instance, I see no way to find out in advance if this exception will get thrown, without possibly hitting the database.

There are a couple workarounds:

  1. Reattach all cached objects at the start of every transaction.
  2. Catch the NonUniqueObjectException and then call session.load(object.class, object.getId());

Neither of these are as clean as checking the session in advance for an object class + id.

Is there any way to do that?

解决方案

Session.merge() should do it:

obj = session.merge(obj);

这篇关于休眠:安全地将对象重新连接到会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆