`
zhzhiqun2005
  • 浏览: 220794 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Hibernate 延迟加载的错误 failed to lazily initialize a collection of role

阅读更多
转载自:  http://www.qingsoft.cn/viewthread.php?tid=1175

用户和角色
用户user中有set<role> roles = new hashset<role>(0);
当得到user中的roles集合时,会出现下面的异常:

java代码


    *     org.hibernate.lazyinitializationexception: failed to lazily initialize a collection of role: com.demo.security.entity.user.roles, no session or session was closed  




1. 当时我的解决是:
userdaoimpl.java

java代码

    *     @suppresswarnings("unchecked")     
         
    *     public list<user> queryall(final integer isinitialize) {   
         
    *            
         
    *         return gethibernatetemplate().executefind(new hibernatecallback(){   
         
    *             public object doinhibernate(session session)   
         
    *                     throws hibernateexception, sqlexception {   
         
    *                 query q = session.createquery("from user u left join fetch u.userinfo");   
         
    *                 if(isinitialize == 0)   return q.list();   
         
    *                 else{   
         
    *                     list<user> users = q.list();   
         
    *                     for(user user : users){   
         
    *                         if(isinitialize ==1)   
         
    *                             gethibernatetemplate().initialize(user.getroles());                        
         
    *                     }   
         
    *                     return users;                     
         
    *                 }   
         
    *                 return q.list();   
         
    *             }});   
         
    *     }  


感觉这样写比较麻烦,觉得效率上也不高。
2. 看到网上有的是把lazy=false,在hibernate annotation中也这样的(注意红色部分)

java代码


  
 *     @manytomany(   
         
    *             targetentity = role.class,              
         
    *             cascade =  {cascadetype.persist, cascadetype.merge},   
         
    *             fetch = fetchtype.eager)   
         
    *     @jointable(   
         
    *             name = "user_role",   
         
    *             joincolumns = {@joincolumn(name = "user_id")},   
         
    *             inversejoincolumns = {@joincolumn(name = "role_id")})   
         
    *     @cache(usage = cacheconcurrencystrategy.read_write)   
         
    *     public set<role> getroles() {   
         
    *         return roles;   
         
    *     }  

要是这样,效率更是糟糕(不管要不要某个数据,都会查询出来,很是浪费)
最后看了篇文章:
就是使用filter,过滤所有的链接
如果在使用filter的时候,要配置事务处理,否则会导致session处于只读状态而不能做修改、删除的动作
web.xml

xml/html代码


  
 *     <filter>     
         
    * <filter-name>hibernatefilter</filter-name>     
         
    * <filter-class>     
         
    * org.springframework.orm.hibernate3.support.opensessioninviewfilter      
         
    * </filter-class>     
         
    * </filter>     
         
    *      
         
    * <filter-mapping>     
         
    * <filter-name>hibernatefilter</filter-name>     
         
    * <url-pattern>*.action</url-pattern>     
         
    * </filter-mapping>  


上面的fetch = fetchtype.eager 改成 fetch = fetchtype.lazy
是这样解释的:
spring为我们解决最让人头痛的难题之一,hibernate的session的关闭与开启问题。
hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 hibernate session 范围之内进行。如果 service 层返回一个启用了延迟加载功能的领域对象给 web 层,当 web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 hibernate session 已经关闭,这些导致延迟加载数据的访问异常。而spring为我们提供的opensessioninviewfilter过滤器为我们很好的解决了这个问题。opensessioninviewfilter的主要功能是使每个请求过程绑定一个 hibernate session,即使最初的事务已经完成了,也可以在 web 层进行延迟加载的操作。opensessioninviewfilter 过滤器将 hibernate session 绑定到请求线程中,它将自动被 spring 的事务管理器探测到。所以 opensessioninviewfilter 适用于 service 层使用hibernatetransactionmanager 或 jtatransactionmanager 进行事务管理的环境,也可以用于非事务只读的数据操作中。
request-->open session-->打开连接、开始事务-->持久操作-->渲染(关闭连接、session)-->response
其中一些过程省略了,不是很关心。
分享到:
评论

相关推荐

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

    延迟加载 - 没有 SEO 负面影响 Qazy 是一个图像延迟加载器,并且与库无关(没有 jQuery)。 Qazy 消除了。 这就是它与其他惰性加载器的不同之处。 尽快在网页中加载脚本,以便它可以开始跟踪图像并延迟加载它们。 ...

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

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

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

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

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

    延迟安装昂贵的组件,直到占位符组件滚动到视图中为止。 安装 npm install --save react-lazily-render 用法 () import React from 'react' ; import LazilyRender from 'react-lazily-render' ; ...lots of ...

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

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

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

    OSGI in Action

    9.3 Starting bundles lazily 314 Understanding activation policies 315 ■ Using activation policies 316 9.4 Summary 317 10 Managing applications 319 10.1 Deploying bundles 320 Introducing management ...

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

    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 用法 import getAllFiles from 'get-all-files' // Get array of filenames ...

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

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

    实现任意多个视图内容的滚动视图

    源码实现了怎样支持延迟加载(lazily load),可以任意多个视图内容的ScrollView。所谓延迟加载,即只加载需要显示的页面内容,即按需加载,从而当需要加载许多视图内容时,不会消耗过多内存。也支持循环滚动视图。...

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

    Lazy ScrollView(iPhone源代码)

     支持延迟加载(lazily load) 任意多个视图内容的ScrollView。所谓延迟加载,即只加载需要显示的页面内容,即按需加载,从而当需要加载许多视图内容时,不会消耗过多内存。也支持循环滚动视图。 Code4App编译测试...

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

    stream.js Javascript

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

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

    A way to think about system design Could I do this lazily/speculatively? When would it pay?Steps toward a sound theory of laziness or speculationI am not presenting such a theory12 December 2006 ...

Global site tag (gtag.js) - Google Analytics