hibernate延迟加载org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.javakc.hibernate.onetomany.entity.DeptEntity.emp, could not initialize proxy – no Session

public static void main(String[] args) {
 
  DeptEntity dept = getDept(“402882e762ae888d0162ae888e420000”);

五月 09, 2017 10:17:23 上午 org.apache.struts2.dispatcher.Dispatcher error
严重: Exception occurred during processing request: failed to lazily initialize a collection of role: com.oaec.entity.Student.scores, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.oaec.entity.Student.scores, no session or session was closed
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:394)
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:386)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:379)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:113)
    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:403)
    at Serializer_1.write1(Unknown Source)
    at Serializer_1.write(Unknown Source)
    at com.alibaba.fastjson.serializer.ListSerializer.write(ListSerializer.java:127)
    at com.alibaba.fastjson.serializer.JSONSerializer.write(JSONSerializer.java:374)
    at com.alibaba.fastjson.JSON.toJSONString(JSON.java:394)
    at com.alibaba.fastjson.JSON.toJSONString(JSON.java:382)
    at com.oaec.action.StudentAction.someStu(StudentAction.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at com.oaec.utils.MyFilter.doFilter(MyFilter.java:30)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.proces
s(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

缘由:在延迟加载的意况下,使用有个别属性时,但session已经倒闭。

org.hibernate.LazyInitializationException: could not initialize proxy –
no Session
    at
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
    at
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
    at
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:191)
    at
com.bawei.entity.Dogtype_$$_javassist_0.getName(Dogtype_$$_javassist_0.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:99)
    at
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:184)
    at
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    at
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:950)
    at
org.apache.jsp.select_jsp._jspx_meth_c_005fforEach_005f0(select_jsp.java:202)
    at org.apache.jsp.select_jsp._jspService(select_jsp.java:133)
    at
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
    at
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    at
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:747)
    at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:485)
    at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:410)
    at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:337)
    at
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
    at
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
    at
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:374)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:278)
    at
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
    at
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
    at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.inv
oke(AuthenticatorBase.java:505)
    at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
    at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1083)
    at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:640)
    at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:744)

no Session难点,即延迟加载

推迟加载的标题是指当大家调用完action中的某些方法,在jsp页面要体现我们想要的新闻的时候,发现在dao中开垦的session已经停业了。

正如图,第一个箭头表示的是大家透过前台页面重返action,action会通过service层调用dao去访问数据库,当从数据库中把值抽出来以往回来到action中,再再次来到到前台页面中去。咱们明白,唯有我们在调用某些类getter()方法的时候才会展开session,可惜的是,在hibernateTemplate中注入的sessionFactory在action再次来到到前台页面前早就停业了,也正是以那时候候再前台页面调用getter()方法,想要张开session,不过sessionFactory已经关闭了,所现在台就能够报错,彰显no
session。意思便是找不到session。

 图片 1

以那个时候候能够运用以下二种办法解决:

1、 
将pojo类中的fetch的lazy改成eager,那个时候要是你的操作页面中牵涉了八个外键关系的话,将要把那多少个外键关系的fetch的lazy都改成eager。这里的lazy是代表懒加载的意思,相当于说在询问三个表的音信的时候,不会把事关的表的音信寻找出来。而风流倜傥旦改成eager的话,就意味着说把涉及的表的新闻也整个加载出来。很醒目,那样的操作会加载一些我们压根就没有必要的操作,也说不定大家只须求加载某张表的音讯的时候,却自动的把关系的表加载出来。所以这种操作质量是比相当糟糕的,不建议接收。

2、 
配置过滤器openSessionInViewFilter,从名称想到所包蕴的意义,那一个过滤器是指把在页面中开拓session的劳动,也正是说延迟session打开的情状,在前台页面中调用完方法之后再关闭session,配置如下:

<filter>

<filter-name>OpenSessionInView</filter-name>

<filter-class>

org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

</filter-class>

</filter>

<filter-mapping>

         <filter-name>OpenSessionInView</filter-name>

         <url-pattern>/*</url-pattern>

</filter-mapping>

要小心的是这几个过滤器要安插到struts的过滤器的眼下,不然就不起成效了,因为安顿在struts过滤器的前边的话,数据已经吸收接纳完成了,也正是说sessionFactory已经关闭了,当时你再来配置说把session延长到view中,已经没意义了,所以要把openSessionInViewFilter配置在struts前边。 不过要注意的是,上边的配置而不是生龙活虎体化的安顿,完整的计划相应是在filter里面配置如下消息:

<filter>

         <filter-name>OpenSessionInView</filter-name>

         <filter-class>

                   org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

         </filter-class>

         <init-param>

                   <param-name>singleSession</param-name>

                   <param-value>true</param-value>

         </init-param>

</filter>

<filter-mapping>

         <filter-name>OpenSessionInView</filter-name>

         <url-pattern>/*</url-pattern>

</filter-mapping>

地方配置的乐趣是代表配置成单例的session。不过假若按上述配置来讲,在承袭session的操作中是会产出难题的,而假若不布署成单例的话,品质是极低的。所以这些点子也不提议。

3、  手工操作(建议)

a)   在action中操作

在action中操作指的是大家在传递对象到前台页面(这里首借使jsp)的时候,多传递一些对象到前台去。比如在action中我们须求传递question对象到前新北张开展现,但是同不时候也须要搜索出那一个标题所属的档期的顺序type,此时就足以在页action中除去传递question对象之外,再借助那几个question的任何属性(如tid)来查找到相应的type,再把type对象传递到页面中。也就那样做相比较勤奋的是除了自个儿要在dao中加措施外,若是四个页面管理着超级多少个数据表的话,传递的靶子属性相对就超级多了。

b)   在daoimpl中操作(刚毅提议)

在daoimpl中开展手工业安装是自己感觉最合适的形式,也是相比较偏重的风流倜傥种。用这种方法的话,在daoimpl的操作中,将在动用hibernateCallback的里边类措施了。相当于说调用super.getHibernateTemplate().execute()方法,编写内部类,在得到二个list会集之后,抽出集结的对象,调用要用到的关联类的getter()方法,就足以张开session了,平时不要调用主键的getter()方法。

范例:

public Question findById(final Integer id) throws Exception {

                   return super.getHibernateTemplate().execute(

                                     new HibernateCallback<Question>() {

                                               @SuppressWarnings("unchecked")

                                               public Question doInHibernate(Session session)

                                                                 throws HibernateException, SQLException { // 用hibernateCallBack

                                                        String hql = "From Question AS q WHERE q.qid=?"; // 构建hql语句

                                                        Query query = session.createQuery(hql); // 创建query

                                                        query.setInteger(0, id); // 设置占位符

                                                        List<Question> all = query.list(); // 得到具体的list集合,里面只存放一个question对象

                                                        if (all.size() > 0) { // 集合不为空

                                                                 Question vo = all.get(0); // 取出question对象

                                                                 vo.getType().getTitle();

// 调用type 的getTitle 方法,这样会把type 相关的session 打开,在jsp 调用时数据还可以调用

                                                                 vo.getAnswers().size();

// 调用getAnswers() 方法,把session 打开,消除延迟加载

                                                                 if (vo.getAnswer() != null) { // 如果存在最佳答案

                                                                           vo.getAnswer().getContent(); // 消除延迟加载

                                                                 }

                                                                 return vo; // 返回vo

                                                        }

                                                        return null;

                                               }

                                     });

         }

  //dept.getEmp()获得子表的笔录集结
  System.out.println(dept.getEmp());

懒加载分外.

鸡犬不留办法:

 

}

其风姿罗曼蒂克荒诞的在于在风流倜傥对多时启用懒加载,可能在用load获取二个对象,况兼未有在web.xml中张开配置.

1.把load改成get,直接加载全部属性。

消除方案

private static DeptEntity getDept(String did){
  Session session = sessionFactory.openSession();
  DeptEntity dept = (DeptEntity)session.get(DeptEntity.class, did);
  session.close();
  return dept;
}

需要在web.xml中配置

2.拿走对象开展一遍判定,若是指标未有开端化,就进展三次开首化。

  <many-to-one name=”dogtype” class=”com.bawei.entity.Dogtype”
fetch=”join” lazy=”false”>
            <column name=”type_id” />
        </many-to-one>

 

<!-- openSessionInViewFilter -->
    <filter>
        <filter-name>openSessionInViewFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
        <init-param>
            <param-name>singleSession</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
if (!Hibernate.isInitialized(obj)) {
            Hibernate.initialize(obj);
        }

运作结果:

在意这段配置必要在struts配置的前边.

3.在小布署里扩张lizy属性取值false

Exception in thread “main” org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
com.javakc.hibernate.onetomany.entity.DeptEntity.emp, could not
initialize proxy – no Session
at
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at
org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
at
org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
at
org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:326)
at java.lang.String.valueOf(String.java:2827)
at java.io.PrintStream.println(PrintStream.java:771)
at
com.javakc.hibernate.onetomany.action.TestAction.main(TestAction.java:74)

4.赢获得对象后,手动先调用叁次后边恐怕用到的性质,以此博得全套属性值。

 

聚焦延迟加载开端化退步,不可能早先化多个代理。正是集聚在非意气风发对风华正茂对象关系中,为了省去能源是暗中认可延迟加载,而get方法又是非延迟加载,所以在试行完一遍数据库查询后就实行session.close();关闭了session,而集结是延迟加载,在动用集适那个时候候再加载,当时session已经关闭,所以得不到代办。清除办法:可以在主表的hbm配置文件中,在<set>标签里设置lazy=”false”,集合就不推迟加载了,因而在施行get方法时,会集也收获到了,就不会现出延迟加载难题了。

相关文章