Hibernate:延迟加载不适用于集合上的一对多映射 [英] Hibernate: lazy-loading doesn't work on one-to-many mapping on set

查看:78
本文介绍了Hibernate:延迟加载不适用于集合上的一对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring和Hibernate一起用于为Liferay门户服务器开发Portlet.我现在基本上有两个实体,A和B,其中A可能包含许多B.因此,这是两者之间的一对多映射.

I'm using Spring together with Hibernate for developing a Portlet for the Liferay portal server. I now have basically two entities, A and B, where A possibly contains many B's. So this goes to a one-to-many mapping between the two.

<set cascade="all" lazy="true" name="comments" order-by="creationDate desc">
   <key column="lfpn_pinboardentries_idPinboardEntry" not-null="true"/>
   <one-to-many class="Comment"/>
</set>

在DAO层中实体A的相应DAO中,我继承了spring提供的"HibernateDaoSupport",因此典型的数据检索如下所示:

In the corresponding DAO of entity A in the DAO layer, I'm inheriting from "HibernateDaoSupport" provided by spring, and so a typical retrieval of data looks like the following:

...
public A getA(long id) {
  return (A) getHibernateTemplate().get(A.class, id);
}
...

如果我有"lazy = false",一切都可以正常工作,但是一旦我切换到"lazy = true",就会出现以下错误:

Everything works fine if I'm having "lazy=false", but as soon as I'm switching to "lazy=true" it gives me the following error:

org.hibernate.LazyInitializationException:无法延迟初始化角色集合:com.lifepin.entities.PinboardEntry.comments,没有会话或会话被关闭

有人建议什么可能是问题或提示如何解决吗?

Does anyone have a suggestion what could be the problem or hints how to solve it?

谢谢!

推荐答案

如果已在一个请求中加载了对象,则通常会收到此错误,然后在不访问延迟加载的属性的情况下将对象保存在会话中.如果然后您在另一个请求中尝试访问延迟加载的属性,则会收到此异常.

You usually get this error if you have loaded the object in one request, then without accessing the lazy loaded property, saved the object in session. If you then in a different request try to access the lazy loaded property you will get this exception.

简单地说:最初加载对象的Hibernate会话已关闭.在另一个Hibernate会话中访问此对象的延迟加载的属性时,将导致此异常.

Simply put : the Hibernate session in which the object was initially loaded has closed. On accessing the lazily loaded property of this object in a different Hibernate session causes this exception.

您必须将对象重新加载到当前的Hibernate会话中,才能延迟加载属性

You will have to reload your object into the current Hibernate session to be able lazily load a property

这篇关于Hibernate:延迟加载不适用于集合上的一对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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