`

failed to lazily initialize a collection of role问题

    博客分类:
  • Java
阅读更多

今天遇到了这样一个问题

 

Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed

 
在网上找了好久终于找到了一个较全的解决方法。具体如下:

 

 

   "org.hibernate.LazyInitializationException: could not initialize proxy"延迟抓取出的错,hb3对many-to-one的默认处理是lazy = "proxy",把所有many-to-one,one-to-one都加上lazy="false"...

 这个方法理论上没错,但是会让人产生误解,使人以为只是修改<set>中的lazy值,照做后依然会报错,看看下面的文章也许就明白了(注意最后一行红色标记)!

  lazy initialization

  集合(不包括数组)是可以延迟初始化的,意思是仅仅当应用程序需要访问时,才载入他们的值。

 

s = sessions.openSession();
User u = (User) s.find("from User u where u.name=?", userName,
Hibernate.STRING).get(0);
Map permissions = u.getPermissions();
s.connection().commit();
s.close();
Integer accessLevel = (Integer) permissions.get("accounts"); //Error!

 

 

  因为在commit之前,permissions没有被用到,permission没有被初始化,而session被close了,导致permissions永远都无法load data.

  解决办法:吧最后一行一道session被提交之前.

  设置:

 

<set name="names" table="NAMES" lazy="true" order-by="name asc">
	<key column="group_id"/>
	<element column="NAME" type="string"/>
</set>

 

 

  ==================================

  在做Spring1.2 + Hibernate 3 + struts demo时候遇到一个问题,编辑用户数据时候

  用com.jeedev.service.dao.hibernate.UserHibernateDao 中 public TSysuser getUser(int userid) { } 方法,总是不能正常显示编辑数据。具体表现为:

  参考 com.jeedev.service.dao.hibernate.UserHibernateDao 第32-45行

  java代码:

 

public TSysuser getUser(int userid) {
  if (this.getHibernateTemplate() == null) {
System.out.println("error at there");
return null;
}
  TSysuser edituser= (TSysuser) getHibernateTemplate().load(TSysuser.class, new Integer(userid));
  System.out.println(edituser.getUsername());
System.out.println(edituser.getDeptno());
  return edituser;
}

 

 

  如果删除上面的java代码:

 

System.out.println(edituser.getUsername());
System.out.println(edituser.getDeptno());

 

 

  在点击编号,修改时候就会出现错误:

   [org.hibernate.LazyInitializationException] - could not initialize proxy - the owning Session was closed

  org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closed
 

  经过在javaeye论坛大家一致认为 是hibernate lazy的原因

  在WEB级别应用时候,会出现意想不到的lazy错误,解决方法就是 设置 lazy="false" 例:

  <hibernate-mapping>

  <class name="com.jeedev.hb.TSysuser" table="t_sysuser" lazy="false">
 

 

还有一种解决方法

2、对于查询中如果用的是xxx.load(class,id)则改为xxx,get(class,id)。在web.xml文件中加入

<filter>
  <filter-name>hibernateFilter</filter-name>
  <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>

  <init-param>
            <param-name>singleSession</param-name>
            <param-value>false</param-value>
        </init-param> 

<!-- 这个--  <init-param>一定要加不然很可能会报 错:org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER) - turn your Session into FlushMode.AUTO or remove 'readOnly' marker from transaction definition
>
</filter>

<filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>*.mmg</url-pattern>
</filter-mapping>
 
分享到:
评论
4 楼 u010467022 2013-12-24  
改为xxx,get(class,id)也不行,唯有lazy=false
或者注解里设置为fetch=FetchType.LAZY这样才行
3 楼 猜不透 2012-08-24  
哥们,及时雨啊
2 楼 luhan158 2011-12-09  
额,看不懂多少
1 楼 macrotea 2011-04-07  
有点乱,建议排版好

相关推荐

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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

    svc.rar_Will

    Will be lazily created when running layout tests.namespace content.

Global site tag (gtag.js) - Google Analytics