java Hibernate:安全地将对象重新附加到会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2730388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:34:16  来源:igfitidea点击:

Hibernate: Safely reattach an object to the session

javahibernate

提问by Rob

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).

我通过在地图中存储(可能分离的)对象来维护跨休眠会话的对象缓存。当缓存命中时,我测试对象是否已经是会话的一部分Session.contains(object)。如果没有,我用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.

问题是,如果先前在会话中加载了相同的对象,则会抛出 org.hibernate.NonUniqueObjectException。给定一个分离的实例,我看不出有没有办法提前知道这个异常是否会被抛出,而不可能访问数据库。

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());
  1. 在每个事务开始时重新附加所有缓存的对象。
  2. 捕获 NonUniqueObjectException 然后调用 session.load(object.class, object.getId());

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

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

Is there any way to do that?

有没有办法做到这一点?

回答by Raj

Session.merge() should do it:

Session.merge() 应该这样做:

obj = session.merge(obj);

回答by Pascal Thivent

I'm maintaining a cache of objects across hibernate sessions

我正在跨休眠会话维护对象缓存

Not a direct answer but why don't you use Hibernate L2 cache for this instead of reinventing the wheel?

不是直接的答案,但为什么不为此使用 Hibernate L2 缓存而不是重新发明轮子呢?