`
mangoo1
  • 浏览: 19258 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

转:failed to lazily initialize a collection of role

阅读更多

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一个个的往数据库里加。这样便不会出问题了。



解决方法:

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>

<!-- open session in view filter -->
    <filter>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <!--<filter-class>org.itec.village.filter.SessionManager</filter-class>-->
        <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>sessionFactoryBeanName</param-name>
            <param-value>org.sakaiproject.springframework.orm.hibernate.GlobalSessionFactory</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <servlet-name>FacesServlet</servlet-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

</web-app>

第2种解决方法:

Hibernate.initialize()强制加载关联对象

分享到:
评论

相关推荐

    JSON序列化Redis读取出错问题解决方案

    首先,不要尝试将整个Collection直接转换为List,而是应该遍历Collection,将每个元素(此时应为一个JSON字符串)单独反序列化为`BookCatalog`对象。以下是一个修正后的示例: ```java // 从Redis读取缓存,直接...

    Packt.Mastering.Csharp.and.NET.Programming

    - **A Quick Tip on the Execution and Memory Analysis of an Assembly in Visual Studio 2015**: Using tools like the Visual Studio Profiler to analyze the memory usage and performance of .NET ...

    Git-2.21.0-64-bit.zip

    * "git fetch" that grabs from a group of remotes learned to run the auto-gc only once at the very end. * A handful of Windows build patches have been upstreamed. * The code to read state files ...

    广东省广州市2018年中考英语学科模拟题十六20180709274

    3. 冠词:"a good worker",不定冠词a用于表示泛指,此处表示“一个好工人”。 4. 形容词与过去分词的区别:"Although surprised",形容词surprised用于表示人的感受。 5. 连词:"because he really needed help",...

    react-lazily-render:延迟安装昂贵的组件,直到将占位符组件滚动到视图中为止

    npm install --save react-lazily-render 用法 () import React from 'react' ; import LazilyRender from 'react-lazily-render' ; ...lots of content... &lt; LazilyRender xss=removed&gt; } content = { ...

    JavaScript Concurrency pdf 无水印 0分

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

    springframework.5.0.12.RELEASE

    Exporting a lazily initialized bean (which implements SelfNaming and is annotated with ManagedResource annotation) gives IllegalStateException [SPR-17592] #22124 MockHttpServletRequest changes Accept-...

    Pandas Cookbook 2017 pdf 2分

    How to get the most out of this book Conventions Assumptions for every recipe Dataset Descriptions Sections Getting ready How to do it... How it works... There's more... See also Reader feedback ...

    2019_2020学年高中英语Unit4BodyLanguageperiod2WarmingUp&Reading2课件新人教版必

    例如,"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 ...

    Android代码-clojure-jsr223

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

    Free Hex Control

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

    广东省深圳市文汇中学2015届九年级英语上学期第7周周末作业(答案不全) 牛津深圳版

    `lazily`:金鱼慵懒地(lazily)成群结队地在水面下游动。 - 15. `coats`:他们给前门刷了三层(coats)油漆。 2. **关键短语或词组**: - 1. `come along`:一起来,过来。 - 2. `a novel called…`:一本叫做...

    react-lazily-img:React Wrapper组件使用IntersectionObserver API延迟加载图像

    懒惰地ReactIMG React Lazily IMG是一个React Wrapper组件,用于延迟加载图像。 目标是使用方便且已知的标准HTML标记,并只是延迟加载它们。特征图片标签和IMG srcset支持Webp检测占位符HTML && CSS图像支持下载图像...

    Redis的Scala客户端Scredis.zip

    // Subscribes to a Pub/Sub channel using the internal, lazily initialized SubscriberClient redis.subscriber.subscribe("My Channel") {  case message @ PubSubMessage.Message(channel, ...

    spring-net-reference.pdf

    - **Setting a reference using the members of other objects and classes**:演示了如何通过其他对象或类的成员设置引用。 - **Provided IFactoryObject implementations**:列出了一些预定义的`IFactoryObject`...

    Android代码-Kodein-DI

    Kodein is a very simple and yet very useful dependency retrieval container. it is very easy to use and configure. Kodein works: On the JVM. On Android. On Javascript (both in the browser and on Node....

    初中英语第六册(北京版)

    - **例句:** 我在厨房里找到了一盒火柴 (a box of matches),准备用来点蜡烛。 2. **围裙 (apron)** - **定义:** 一种穿戴于胸前,用于保护衣物免受污损的布料。 - **例句:** 一位身穿白色围裙 (white apron)...

    甘肃省定西市临洮县第四中学2020学年八年级英语下学期第一次月考试题(无答案) 人教新目标版.doc

    2. 形容词转副词,如lazy变为lazily,常用来修饰动词。 3. 数词转换为序数词,如twenty变为twentieth,表示顺序。 4. 名词转形容词,如dirt变为dirtY,用以形容事物的状态。 5. 名词转形容词,如sun变为sunny,描述...

    cinnamon:一个简单的部署工具

    名称 Cinnamon-简约的部署工具 概要 use strict; use warnings; # Exports some commands use Cinnamon::DSL; my $application = 'My::App';...# Lazily evaluated if passed as a code set lazy_value =&gt; sub { #.

    Qazy:延迟加载 - 没有 SEO 负面影响

    -- data-qazy is set to true means to load it lazily. Set it to false if you don't want to load it lazily. --&gt; &lt;!-- A default placeholder is used. To change the placeholder, assign the variable ...

Global site tag (gtag.js) - Google Analytics