failed to lazily initialize a collection of role: XXXXXXXX no session or session was closed2007-05-11 10:47这个异常大致意思是说在多对一的时候(并且lazy="false"),对象的实例失败,多数出现的情况有
1、粗心造成
实例对象类名写错之类的
2、逻辑错误
如之前就已经传递过来一个实体对象,然后调用实体对象的方法时牵涉到1对多的情况,但此时SESSION已经关闭,所以根本无法进行一对多的操作。
3、设计到跨度的问题:
这样打比方有多个实体对象,他们直接或则间接的有关联。比如有4个实体,分别是广告信息、广告、广告问答题、广告商:他们之间的关系为:
广告商 1:n 广告
广告 1:n 广告问答题
广告商 1:n 广告商信息
大家可以看到广告和广告商信息是没有直接关系的。但我要添加广告的时候我就必须将广告商的实体做为条件。那么这么一来广告商信息可能间接的就必须用上。下面看我的操作:
ad(广告),subject(题目)
Ad ad = new Ad();
ad.setAdProd(adform.getAdProd());
ad.setIndustry(industry);
ad.setAdPicture(pagefile.getFileName());
ad.setAdFlack(adform.getAdFlack());
ad.setAdDv(dvfile.getFileName());
ad.setAdContent(adform.getAdContent());
ad.setGray(gray);
ad.setAdDate(new Date());
ad.setOnlinetime(new Long(0));
//以上为广告的基本信息填写,而重要的是看下面一句,在这里我的思路是subjectFormList是一个动态提交的表单,里面有若干个广告问答题。我将这些问答题变为一个Set,然后作为ad的一个属性。
Set<Subject> subjectset=getSubjectSet(subjectFormList,ad);
ad.setSubjects(subjectset);
//然后提交,makePersistent是一个封装的方法,用途就是save()啦。addao是一个DAO,里面有ADUS。
addao.makePersistent(ad);
表面上看来很符合逻辑,只要我们在ad的映射里面加上对subject的级联更新就可以完成这项操作。但实际上会发生我们意想不到的问题,来让我们看一下getSubjectSet()的内容:
public Set getSubjectSet(List<SubjectForm> subjectlist,Ad ad)
{
Set<Subject> set=new HashSet<Subject>(0);
Subject subject;
for(Iterator<SubjectForm> it=subjectlist.iterator();it.hasNext();)
{
subject=new Subject();
SubjectForm sf=it.next();
subject.setSuContent(sf.getSucontent());
subject.setSuOption(sf.getSuoption());
subject.setSuResult(Arrays.deepToString(sf.getSuresult()));
subject.setSuType(String.valueOf(sf.getSutype()));
subject.setAd(ad);
set.add(subject);
}
return set;
}
我们在这个方法上设一个断点然后跟踪,之后你会发现断点在set.add(subject)只后就会出failed to lazily initialize a collection of role: XXXXXXXX no session or session was closed这个异常,并且这个异常还是出在了广告商的广告信息上 gray.messages。是不是很不可理解?这也是Hibernate的懒汉机制问题。没有任何一样技术是完美的。那我们该怎么处理这样的问题。有很多人以为我们在广告商对广告商信息的隐射上加lazy="false"这样在对gray操作会对messages进行关联,并查询时提出数据。但你会发现改完之后会出现org.hibernate.LazyInitializationException: illegal access to loading collection这个异常。并切lazy="false"是我们不推荐的一种方法。他会降低你的查询效率。
对于这样的情况最好的解决办法就是不要偷懒,对一个实体进行操作的时候就该用那个实体的DAO,即应该有2句HQL。如下把getSubjectSet()改一改:
public void getSubjectSet(List<SubjectForm> subjectlist,Ad ad)
{
Set<Subject> set=new HashSet<Subject>(0);
SubjectDAO subjectdao=DAOFactory.getDao(SubjectDAO.class);
for(Iterator<SubjectForm> it=subjectlist.iterator();it.hasNext();)
{
Subject subject=new Subject();
SubjectForm sf=it.next();
subject.setSuContent(sf.getSucontent());
subject.setSuOption(sf.getSuoption());
subject.setSuResult(Arrays.deepToString(sf.getSuresult()));
subject.setSuType(String.valueOf(sf.getSutype()));
subject.setAd(ad);
subjectdao.makePersistent(subject);
//set.add(subject);
}
}//遍历出所有subject一个个的往数据库里加。这样便不会出问题了。
1、OpenSessionInView模式:
以下有2种方法,第1种是结合SPRING,第2种是采用了拦截器
Spring+Hibernate中, 集合映射如果使用lazy="true", 当PO传到View层时, 出现未初始化session已关闭的错误,只能在dao先初始化
parent.getChilds().size();
Spring提供Open Session In View来解决这个问题, 有两种方式
1. Interceptor <!--</span><span style="COLOR: rgb(0,128,0)"> =========== OpenSession In View pattern ==============</span><span style="COLOR: rgb(0,128,0)">-->
<bean id="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors" ref="openSessionInViewInterceptor"/>
<property name="mappings">
<props>
......
</props>
</property>
</bean>
2. Filter <web-app>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
</web-app>
分享到:
相关推荐
"checking out paths out of the index and/or a tree-ish to work on advancing the current history" out of the single "git checkout" command. * "git branch --list" learned to always output the ...
/ Errrrr...Actually, I hesitate to release the source code of this control, / Because when I checked after completion, I found that it's really ugly! Putting all / graphic codes in the CDraw class ...
- **Context**: Context in computing refers to the specific environment or settings under which a particular operation occurs. This includes variables, registers, and other resources that the running ...
lazily. Copyright (c) 2009 Armando Blancas. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ...
npm install --save react-lazily-render 用法 () import React from 'react' ; import LazilyRender from 'react-lazily-render' ; ...lots of content... < LazilyRender xss=removed> } content = { ...
Apply the core principles of concurrency to both browser and server side development Explore the latest tools and techniques at the forefront of concurrent programming, including JavaScript promises, ...
`lazily`:金鱼慵懒地(lazily)成群结队地在水面下游动。 - 15. `coats`:他们给前门刷了三层(coats)油漆。 2. **关键短语或词组**: - 1. `come along`:一起来,过来。 - 2. `a novel called…`:一本叫做...
- **Easier configuration of declarative transactions in XML**: 在XML配置中简化了声明式事务的配置。 - **JPA**: 支持Java Persistence API,为持久化层提供了一致性的API接口。 - **Asynchronous JMS**: 提供...
懒惰地ReactIMG React Lazily IMG是一个React Wrapper组件,用于延迟加载图像。 目标是使用方便且已知的标准HTML标记,并只是延迟加载它们。特征图片标签和IMG srcset支持Webp检测占位符HTML && CSS图像支持下载图像...
KOtlin DEpendency INjection Kodein is a very simple and yet very useful dependency ...Easily bind classes or interfaces to their instance or provider Easily debug your dependency bindings and rec
Exporting a lazily initialized bean (which implements SelfNaming and is annotated with ManagedResource annotation) gives IllegalStateException [SPR-17592] #22124 MockHttpServletRequest changes Accept-...
Table of Contents Preface What this book covers What you need for this book Running a Jupyter Notebook Who this book is for How to get the most out of this book Conventions Assumptions for every ...
例如,"After about ten minutes of waiting, I saw a middle-aged man enter her courtyard looking back carefully."中,"After about ten minutes of waiting"作为时间状语,描述动作发生的时间;"looking back ...
- "more or less"意为"或多或少","no less than"表示"绝不少于,多达"。 - "teaspoonful"指的是"一满茶匙"的量,如"a teaspoonful of tea"。 - "pity"表示"遗憾",感叹句中可使用"What a pity!"表达惊讶或惋惜。...
// Subscribes to a Pub/Sub channel using the internal, lazily initialized SubscriberClient redis.subscriber.subscribe("My Channel") { case message @ PubSubMessage.Message(channel, ...
获取所有文件 具有延迟同步和异步迭代器支持的出色的快速递归目录搜寻器。 安装 支持Node.js版本10及更高版本。 $ npm i get-all-files ...path/to/dir/or/file` ) ) { // Could break early on some condition a
- **Lazily-Instantiated Beans**:介绍了延迟加载Bean的概念,即在真正需要的时候才加载Bean实例。 - **Autowiring Collaborators**:通过autowire属性自动装配Bean之间的依赖关系。 - **Checking for Dependencies...
- **例句:** 我在厨房里找到了一盒火柴 (a box of matches),准备用来点蜡烛。 2. **围裙 (apron)** - **定义:** 一种穿戴于胸前,用于保护衣物免受污损的布料。 - **例句:** 一位身穿白色围裙 (white apron)...
The aim is to provide, lazily evaluated, pull-based datastream support with the same naming as in RxJava mainly for the pre-Java-8 world. The Stream API in Java 8 is not exactly the same thing because...