java 分离对象中的休眠延迟加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3862658/
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-30 03:44:56  来源:igfitidea点击:

Hibernate lazy loading in detached objects

javahibernatelazy-loading

提问by Clinton Bosch

I have created a class in which I have set some of it's fields (other entities) to be LAZY loaded. Now I need to use this object after it has been detached from the session, so I obviously need to make sure all the fields that I need are populated before detaching it. I tried just calling the getters to these lazy fields but that didn't seem to work. Anyone have an idea how to force these fields to be loaded?

我创建了一个类,在该类中我将它的一些字段(其他实体)设置为 LAZY 加载。现在我需要在它与会话分离后使用这个对象,所以我显然需要确保在分离它之前填充我需要的所有字段。我尝试将 getter 调用到这些惰性字段,但这似乎不起作用。任何人都知道如何强制加载这些字段?

采纳答案by Bozho

Hibernate.initialize(yourObject)

will force-initialize the object/collection that is passed to it. You need an active session for this.

将强制初始化传递给它的对象/集合。为此,您需要一个活动会话。

If the entity is detached, you'd have to re-attach the object (using merge(..)) to an active session and then initialize it.

如果实体已分离,则必须将对象(使用merge(..))重新附加到活动会话,然后对其进行初始化。

回答by pakore

You can reattach it to the session. This is the normal way.

您可以将其重新附加到会话中。这是正常的方式。

session.update(yourObject); //This reattachs the object to the current session.
yourObject.someGetter(); //This will work now.

回答by Prateek Singh

<prop key="hibernate.enable_lazy_load_no_trans">true</prop> 

you can add this line into your configuration file,it can fetch your lazy objects even it is detached,but it should be use post 4.1.7 version as there are some connection leakage issue with previous version.see here

您可以将此行添加到您的配置文件中,即使它被分离,它也可以获取您的惰性对象,但它应该使用 4.1.7 版本,因为以前的版本存在一些连接泄漏问题。请参见 此处

回答by skytteren

I know that you asked for Hibernate but EclipseLinkhas this feature so it might be worth checking out if you are using JPA and not tied to a given implementation. You might run into other problems migrating to EclipseLink though..

我知道您要求使用 Hibernate,但EclipseLink具有此功能,因此如果您使用的是 JPA 并且未绑定到给定的实现,则可能值得检查一下。不过,您在迁移到 EclipseLink 时可能会遇到其他问题。