`
Java-primer
  • 浏览: 50295 次
  • 性别: Icon_minigender_1
  • 来自: 成都
文章分类
社区版块
存档分类
最新评论

failed to lazily initialize a collection of role: XXXXXXXX no session or session

阅读更多
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>
分享到:
评论

相关推荐

    Git-2.21.0-64-bit.zip

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

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

    Python Cookbook英文版

    2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership ...

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

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

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

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

    Android代码-Kodein-DI

    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

    OSGI in Action

    Loosening things up 221 ■ To bundle or not to bundle? 226 6.3 Summary 229 7 Testing applications 230 7.1 Migrating tests to OSGi 231 In-container testing 231 ■ Bundling tests 232 ■ Covering all the...

    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分

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

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

    get-all-files::high_voltage:具有懒惰同步和异步迭代器支持的快速递归目录搜寻器

    获取所有文件 具有延迟同步和异步迭代器支持的出色的快速递归目录搜寻器。 安装 支持Node.js版本10及更高版本。 $ npm i get-all-files ...path/to/dir/or/file` ) ) { // Could break early on some condition a

    Android代码-ixjava

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

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

    Lazy and Speculative Execution - Microsoft Research - Slides (12th December, 2006)-计算机科学

    Steps toward a sound theory of laziness or speculationI am not presenting such a theory12 December 2006 Lampson: Lazy and Speculative Execution 3Lazy EvaluationWell studied in programming languages ...

    Android组件ViewStub基本使用方法详解

    “A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. When a ViewStub is made visible, or when inflate() is invoked, the layout resource is ...

    node-cached:受Play缓存API启发的用于node.js的简单缓存库

    已缓存 一个简单的缓存库,受启发,偏向于。 该接口仅公开了非常有限的功能,没有对缓存数据的多次获取或删除。...// Set a key using a lazily created promise (or value) kittens . set ( 'my.key' , function

    stream.js Javascript

    stream.js 是一个很小、完全独立的Javascript类库,它为你提供了一个新的...他的这种魔力来自于具有延后(lazily)执行的能力。这简单的术语完全能表明它们可以加载无穷多的元素。(http://www.aqee.net/docs/stream/)

Global site tag (gtag.js) - Google Analytics