解决could not initialize proxy - no Session

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fugushiba/article/details/79981217

问题描述:


org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.zhai.model.sys.Tresource.resources, could not initialize proxy - no Session

    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
    at com.alibaba.fastjson.serializer.CollectionSerializer.write(CollectionSerializer.java:68)
    at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:390)
    at Serializer_1.write1(Unknown Source)
    at Serializer_1.write(Unknown Source)
    at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:390)
    at Serializer_1.write1(Unknown Source)
    at Serializer_1.write(Unknown Source)
    at com.alibaba.fastjson.serializer.JSONSerializer.write(JSONSerializer.java:361)
    at com.alibaba.fastjson.JSON.toJSONString(JSON.java:393)
    at com.alibaba.fastjson.JSON.toJSONString(JSON.java:381)
    at com.zhai.service.ResourceTest.getTreemenu(ResourceTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

导致出现该错误的代码:@ManyToMany(fetch = FetchType.LAZY) 采用了懒加载;


    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "sys_role_resource", joinColumns = { @JoinColumn(name = "resource_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
    @OrderBy("id ASC")
    public Set<Trole> getRoles() {
        return roles;
    }

解决方法:
1、把lazy设成false。这个是最简单的办法,个人认为也是比较笨的方法。因为这是在用效率作为代价。

2、使用OpenSessionInViewFilter。这种方法是将session交给servlet filter来管理,每当一个请求来之后就会开

启一个session,只有当响应结束后才会关闭。如下:
在web.xml配置文件中加上该配置

<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>/*</url-pattern>   
</filter-mapping> 

3、若是单纯的junit 测试的就只需加上 @Trantsactional

    @Autowired
    private ResourceServiceImpl resourceService;
    @Test
    @Transactional
    public void getTreemenu() {
        List<Tresource> l = null;
        l = resourceService.getTremenu(false);
        for (Tresource t : l) {
            System.out.println(JSONArray.toJSONString(t));
        }
    }
}

could not initialize proxy - no Session

10-12

[code=Java]adminrnHibernate: select users0_.users_Id as users1_3_, users0_.users_Dept as users2_3_, users0_.users_State as users3_3_, users0_.users_Accounts as users4_3_, users0_.users_Name as users5_3_, users0_.users_Pwd as users6_3_, users0_.users_Num as users7_3_ from hdErp.dbo.users users0_ where 1=1 and (users0_.users_Accounts like ?) and (users0_.users_Pwd like ?)rnadmin 20$2C$B9$62$AC$59$07$5B$96$4B$07$15$2D$23$4B$70rn部门:1rnadmin YYYYrn2009-10-12 9:49:29 org.apache.catalina.core.StandardWrapperValve invokern严重: Servlet.service() for servlet action threw exceptionrnorg.hibernate.LazyInitializationException: could not initialize proxy - no Sessionrn at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)rn at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)rn at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)rn at com.whhd.entity.users.Dept$$EnhancerByCGLIB$$3a571986.getDeptClass()rn at com.whhd.struts.action.MainAction.bodyLeft(MainAction.java:57)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)rn at java.lang.reflect.Method.invoke(Unknown Source)rn at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)rn at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)rn at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:110)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at com.whhd.util.EncodingFilter.doFilter(EncodingFilter.java:23)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)rn at java.lang.Thread.run(Unknown Source)[/code]rnrn我在session中 获得一个用户的信息,Users为用户表,其中dept为外键 对应部门表 外键ID可以获取到,但是外键的值 获取不到 报could not initialize proxy - no Session错误,我的实体.hbm.xml里 把set 里有改lazy="false" 还是这个问题,我在网上查了下rn rn hibernateFilter rn rn org.springframework.orm.hibernate3.support.OpenSessionInViewFilter rn rn rn hibernateFilter rn *.do rnrn在配置文件中加了这些,后来 又重写了spring的OpenSessionInViewFilte方法rn将private FlushMode flushMode = FlushMode.NEVER;改成private FlushMode flushMode = FlushMode.AUTO;rn结果还是报一样的错误rn请大家帮帮忙...

LazyInitializationException: could not initialize proxy - no Session

05-07

SpringMVC4+JPA+Hibernate4,设置fetch = FetchType.LAZY后,rn报错:[color=#FF0000]org.hibernate.LazyInitializationException: could not initialize proxy - no Session[/color]rnrn我不想设置为 fetch = FetchType.EAGER,如何设置fetch = FetchType.LAZY,成功加载所需要的数据?rn敬请高人指点。rnrn配置文件如下:rnrnweb.xmlrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrnrnrn Web Applicationrnrn rn CharacterEncodingFilterrn org.springframework.web.filter.CharacterEncodingFilterrn rn encodingrn utf-8rn rn rn rn CharacterEncodingFilterrn /*rn rnrn rn zanworn org.springframework.web.servlet.DispatcherServletrn 1rn rn rn zanworn /rn rnrn rn index.htmlrn rnrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrnspring-servlet.xmlrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrnrnrn rn rnrn rnrn rn rnrn rnrn rnrn rnrn rn rn rnrn rn rn rn rn rn rnrn rn rn rn rn rn rn rn rnrn rn rn rn errorrn rn rn rnrn rn rn /WEB-INF/pages/rn rn rn .jsprn rn rnrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrnpersistence.xmlrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrn rn org.hibernate.ejb.HibernatePersistencern rn rn rn rn rn rn rn rn rn rnrn-----------------------------------------------------------------------------------------------------------------------------------------------------rnrn其中两个类,shop(店铺)和商品(product)是一对多关系,我是这样定义:rnProduct.javarn@Entityrn@Table(name = "product")rnpublic class Product extends BaseEntity implements Serializable rnrn private static final long serialVersionUID = 4386742079736072275L;rnrn @Idrn @GeneratedValuern @Column(name = "prod_id")rn private Long prodId;rnrn @ManyToOne(cascade = CascadeType.ALL , fetch = FetchType.LAZY, optional = false)rn @JoinColumn(name = "shop_id")rn private Shop shop;rnrn @Column(name = "prod_name")rn private String prodName;rnrn @Column(name = "prod_desc")rn private String prodDesc;rn rngetter() and setter().....rnrnrnrnShop.javarn@Entityrn@Table(name = "shop")rnpublic class Shop extends BaseEntity implements Serializable rn private static final long serialVersionUID = 2949762130923624926L;rn @Idrn @GeneratedValuern @Column(name = "shop_id")rn private Long shopId;rnrn @Column(name = "shop_name")rn private String shopName;rnrn @Column(name = "shop_desc")rn private String shopDesc;rnrn @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "shop")rn private Set products = new HashSet(0);rnrngetter() and setter().....rnrnrnrn当页面访问$product.shop.shopName就会报错:[color=#FF0000]org.hibernate.LazyInitializationException: could not initialize proxy - no Session[/color]

spring- could not initialize proxy - no Session

08-07

DEBUG - Using SessionFactory 'sessionFactory' for OpenSessionInViewFilterrnDEBUG - Returning cached instance of singleton bean 'sessionFactory'rnDEBUG - Opening single Hibernate Session in OpenSessionInViewFilterrnDEBUG - Opening Hibernate SessionrnDEBUG - opened session at timestamp: 13443286677rnDEBUG - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@a42cc9], property=struts]rnDEBUG - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@a42cc9], property=struts]rnDEBUG - Creating an DefaultActionProxy for namespace / and action name perClaimVouchersrnDEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'rnDEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0'rnDEBUG - Returning cached instance of singleton bean 'claimVoucherBiz'rnDEBUG - Added autowiring by name from bean name 'org.kara.action.ClaimVoucherAction' via property 'claimVoucherBiz' to bean named 'claimVoucherBiz'rnDEBUG - Returning cached instance of singleton bean 'departmentBiz'rnDEBUG - Added autowiring by name from bean name 'org.kara.action.ClaimVoucherAction' via property 'departmentBiz' to bean named 'departmentBiz'rnDEBUG - Returning cached instance of singleton bean 'employeeBiz'rnDEBUG - Added autowiring by name from bean name 'org.kara.action.ClaimVoucherAction' via property 'employeeBiz' to bean named 'employeeBiz'rnDEBUG - Returning cached instance of singleton bean 'positionBiz'rnDEBUG - Added autowiring by name from bean name 'org.kara.action.ClaimVoucherAction' via property 'positionBiz' to bean named 'positionBiz'rnDEBUG - intercept '//perClaimVouchers' rnDEBUG - applied invocation context locale=en_GBrnDEBUG - Entering nullPropertyValue [target=[proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false, com.opensymphony.xwork2.DefaultTextProvider@a42cc9], property=locale]rnDEBUG - before Locale=nullrnDEBUG - Entering nullPropertyValue [target=[proxyTargetClass=false; optimize=false; opaque=false; exposeProxy=false; frozen=false, com.opensymphony.xwork2.DefaultTextProvider@a42cc9], property=struts]rnDEBUG - Bypassing //perClaimVouchersrnDEBUG - Setting static parameters rnDEBUG - Setting params NONErnDEBUG - Setting params rnDEBUG - Validating //perClaimVouchers with method searchClaimVouchers.rnDEBUG - Executing action method = searchClaimVouchersrnERROR - could not initialize proxy - no Sessionrnorg.hibernate.LazyInitializationException: could not initialize proxy - no Sessionrn at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:132)rn at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174)rn at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)rn at org.kara.entity.SysPosition_$$_javassist_1.getNameCn(SysPosition_$$_javassist_1.java)rn at org.kara.action.ClaimVoucherAction.getPosition(ClaimVoucherAction.java:94)rn at org.kara.action.ClaimVoucherAction.searchClaimVouchers(ClaimVoucherAction.java:82)rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:597)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)rn at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)rn at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)rn at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)rn at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)rn at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)rn at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)rn at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)rn at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)rn at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)rn at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)rn at java.lang.Thread.run(Thread.java:619)rnDEBUG - Closing single Hibernate Session in OpenSessionInViewFilterrnDEBUG - Closing Hibernate Sessionrnrn调用方法时老报这个错,特别纠结。您能提供点建议么?谢谢!期待您能快些回复....... 急!急!急!rnrn

急求解决方案【 could not initialize proxy - no Session

03-31

错误:rnorg.apache.jasper.JasperException: org.hibernate.LazyInitializationException: could not initialize proxy - no Sessionrn org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:491)rn org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)rn org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)rn org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)rn javax.servlet.http.HttpServlet.service(HttpServlet.java:717)rn org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:154)rn org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)rn com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:361)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:265)rn com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)rn org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)rn com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)rn com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)rn org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)rn org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)rn org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)rn org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)rnrn

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

03-04

hibernate出现异常,有知道的人,给个解决方案,谢谢rn积分奖励!rnrn2008-03-04 16:51:19 [日志信息] could not initialize proxy - the owning Session was closedrn[color=#3366FF]org.hibernate.LazyInitializationException[/color]: could not initialize proxy - the owning Session was closedrn at org.hibernate.proxy.AbstractLazyInitializer.initialize([color=#3366FF]AbstractLazyInitializer.java:53[/color])rn at org.hibernate.proxy.AbstractLazyInitializer.getImplementation([color=#3366FF]AbstractLazyInitializer.java:84[/color])rn at org.hibernate.proxy.CGLIBLazyInitializer.intercept([color=#3366FF]CGLIBLazyInitializer.java:134[/color])rn at com.orm.MemberLevel$$EnhancerByCGLIB$$54d60d0d.getLevelName()rn at sun.reflect.NativeMethodAccessorImpl.invoke0([color=#3366FF]Native Method[/color])rn at sun.reflect.NativeMethodAccessorImpl.invoke([color=#3366FF]NativeMethodAccessorImpl.java:39[/color])rn at sun.reflect.DelegatingMethodAccessorImpl.invoke([color=#3366FF]DelegatingMethodAccessorImpl.java:25[/color])rn at java.lang.reflect.Method.invoke([color=#3366FF]Method.java:585[/color])rn at org.apache.commons.el.ArraySuffix.evaluate([color=#3366FF]ArraySuffix.java:314[/color])rn at org.apache.commons.el.ComplexValue.evaluate([color=#3366FF]ComplexValue.java:145[/color])rn at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate([color=#3366FF]ExpressionEvaluatorImpl.java:263[/color])rn at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate([color=#3366FF]ExpressionEvaluatorImpl.java:190[/color])rn at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate([color=#3366FF]PageContextImpl.java:922[/color])rn at org.apache.jsp.default_jsp._jspx_meth_bean_message_7([color=#3366FF]org.apache.jsp.default_jsp:900[/color])rn at org.apache.jsp.default_jsp._jspx_meth_logic_present_1([color=#3366FF]org.apache.jsp.default_jsp:845[/color])rn at org.apache.jsp.default_jsp._jspService([color=#3366FF]org.apache.jsp.default_jsp:263[/color])rn at org.apache.jasper.runtime.HttpJspBase.service([color=#3366FF]HttpJspBase.java:97[/color])rn at javax.servlet.http.HttpServlet.service([color=#3366FF]HttpServlet.java:802[/color])rn at org.apache.jasper.servlet.JspServletWrapper.service([color=#3366FF]JspServletWrapper.java:322[/color])rn at org.apache.jasper.servlet.JspServlet.serviceJspFile([color=#3366FF]JspServlet.java:291[/color])rn at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)rn at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)rn at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)rn at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)rn at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)rn at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1085)rn at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:398)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:241)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)rn at com.ricky.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:33)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)rn at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)rn at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)rn at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)rn at java.lang.Thread.run(Thread.java:595)rn2008-03-04 16:51:19 [日志信息] Servlet.service() for servlet jsp threw exceptionrnorg.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closedrn at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:53)rn at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:84)rn at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:134)rn at com.orm.MemberLevel$$EnhancerByCGLIB$$54d60d0d.getLevelName()rn at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rn at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)rn at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)rn at java.lang.reflect.Method.invoke(Method.java:585)rn at org.apache.commons.el.ArraySuffix.evaluate(ArraySuffix.java:314)rn at org.apache.commons.el.ComplexValue.evaluate(ComplexValue.java:145)rn at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:263)rn at org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:190)rn at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:922)rn at org.apache.jsp.default_jsp._jspx_meth_bean_message_7(org.apache.jsp.default_jsp:900)rn at org.apache.jsp.default_jsp._jspx_meth_logic_present_1(org.apache.jsp.default_jsp:845)rn at org.apache.jsp.default_jsp._jspService(org.apache.jsp.default_jsp:263)rn at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)rn at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)rn at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)rn at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)

hibernate提示could not initialize proxy - no Session

05-22

初学hibernate,贴上代码rnpackage com.test.bean;rnrnimport org.hibernate.Session;rnimport org.hibernate.SessionFactory;rnimport org.hibernate.Transaction;rnrnimport com.caijia.util.HibernateUtil;rnrnpublic class StudentTest rnrn public static void main(String[] args) rn Student s = new Student();rn s.setId(1);rn s.setName("student4");rn s.setAge(20);rn SessionFactory sf = HibernateUtil.getSessionFactory();rnrn Session session = sf.openSession();rn Transaction trsct = session.beginTransaction();rn //从数据库里拿出student实体rn Student s1 = (Student) session.load(Student.class, 1);rn //System.out.println(s1.getAge());rn //load出来后直接执行set方法即可修改数据库相对字段的属性值rn s1.setName("s1");rn trsct.commit();rn System.out.println(s1.getName());rn session.close();//关闭sessionrn rn rn //重新得到一个新的sessionrn Session session1 = sf.openSession();rn System.out.println("session1:"+session1);rn s1.setAge(26);rn Transaction trsct1 = session1.beginTransaction();rn //依次执行set和update方法即可修改刚才被load的实体的数据库相对字段的属性值rn session1.update(s1);rn trsct1.commit();rn session1.close();rn sf.close();rnrn rnrnrnrn以上为测试代码,奇怪的是当不注释System.out.println(s1.getAge());这句后,后台能打印出hibernate所执行的sql,但把这句注释掉后执行就会报错;但session1能正常打印出来session1:SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@126b0b91 updates=org.hibernate.engine.spi.ExecutableList@31c46609 deletions=org.hibernate.engine.spi.ExecutableList@5506f265 orphanRemovals=org.hibernate.engine.spi.ExecutableList@3b13f07f collectionCreations=org.hibernate.engine.spi.ExecutableList@1a124026 collectionRemovals=org.hibernate.engine.spi.ExecutableList@24318c29 collectionUpdates=org.hibernate.engine.spi.ExecutableList@30e8ea4f collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@b6f019f unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])rn报错:rnorg.hibernate.LazyInitializationException: could not initialize proxy - no Sessionrn

could not initialize proxy-no session

07-06

不知道怎么回事。我的SessionFactory是在这个类中(ServiceForAdminImpl)创建的,大致情况如下rn-----------------------------------------------------------------------------------------rnpublic class ServiceForAdminImpl extends ServiceAdapterrn staticrnsf = new AnnotationConfiguration().configure().buildSessionFactory();rnServletActionContext.getRequest().getSession().setAttribute("sf", sf); //然后我把它放在session中rnrn rn rnrn-----------------------------------------------------------------------------------------rn另外一个类的情况如下rnpublic class SearchPayRecord extends ServiceAdapter rn rn public Object listPayRecord(Object obj)rn SearchPayRecordAction searchAction = (SearchPayRecordAction)obj;rn rn SessionFactory sf = (SessionFactory) ServletActionContext.getRequest().getSession().getAttribute("sf");rnrn Session session = sf.getCurrentSession();rn session.beginTransaction();rnrnrn AdminInfoBean admin =(AdminInfoBean) ServletActionContext.getRequest().getSession().getAttribute("admin");rn rn Query query = session.createQuery("from PayRecordBean p where p.house.id=:houseId and p.house.admin.id=:adminId")rn .setLong("houseId", searchAction.getHouseId())rn .setInteger("adminId", admin.getId());rnrnrn List record = (List)query.list();rn rn session.getTransaction().commit();rn return record;rn rnrnrnrn-----------------------------------------------------------------------------------------------------rn然后服务器就会报could not initialize proxy-no session这个错误rn但是如果我把session.getTransaction().commit();注释掉,它就不会报错,这是怎么回事rnrnrnrnrnrnrn-----------------------------------------------------------------------------------------

org.hibernate.LazyInitializationException: could not initialize proxy - the owni

09-18

Action:rn[code=Java]rnpublic Cardinfo findById(Long id) rn Session session = HibernateSessionFactory.getSession();rn Transaction tx = null;rn Cardinfo cinfo = null;rn try rn tx = session.beginTransaction();rn cinfo = (Cardinfo) session.load(Cardinfo.class, id);rn tx.commit();rn catch (RuntimeException re) rn tx.rollback();rn log.error("==CardinfoServices findById failed==", re);rn finally rn session.close();rn rn return cinfo;rn rn[/code]rnrn[code=Java]rnString cidLoad = request.getParameter("cidLoad");rn Cardinfo cardinfo = cardinfoSer.findById(new Long(cidLoad));rn cardinfoForm.setCardid(new Long(cidLoad));rn cardinfoForm.setCardname(cardinfo.getCardname());rn cardinfoForm.setPhonenum(cardinfo.getPhonenum());rn cardinfoForm.setCardstate(cardinfo.getCardstate());rn cardinfoForm.setOtherinfo(cardinfo.getOtherinfo());rnrn System.out.println("oid: "rn + cardinfo.getCardownerinfo().getOwnerid());rn System.out.println("oid: "rn + cardinfo.getCardownerinfo().getOwnername());rn[/code]rnrn错误指向这行:rn cardinfoForm.setCardname(cardinfo.getCardname());rnrn于是修改:rn[code=Java]rnpublic Cardinfo findById(Long id) rn Session session = HibernateSessionFactory.getSession();rn Transaction tx = null;rn Cardinfo cinfo = null;rn try rn tx = session.beginTransaction();rn cinfo = (Cardinfo) session.load(Cardinfo.class, id);rn Hibernate.initialize(cinfo);rn tx.commit();rn catch (RuntimeException re) rn tx.rollback();rn log.error("==CardinfoServices findById failed==", re);rn finally rn session.close();rn rn return cinfo;rn rn[/code]rnrn程序还是报错:org.hibernate.LazyInitializationException: could not initialize proxy - the owning Session was closedrnrn错误指向:rnSystem.out.println("oid: "rn + cardinfo.getCardownerinfo().getOwnername());rnrn这该如何解决呢?rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭