7 Replies Latest reply on May 18, 2009 5:41 AM by Avor Nadal

    failed to lazily initialize a collection of role:

    t kumar Newbie

      15:07:00,814 ERROR [LazyInitializationException] failed to lazily initialize a collection of role: com.projectvault.ejb.project.ProjectObject.projectFolderObjects, no session or session was closed
      org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.projectvault.ejb.project.ProjectObject.projectFolderObjects, no session or session was closed
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
      at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
      at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
      at org.hibernate.collection.PersistentBag.toString(PersistentBag.java:459)
      at com.projectvault.to.ProjectTO.toString(ProjectTO.java:388)
      at com.projectvault.service.ProjectService.findByProjectName(ProjectService.java:334)
      at com.projectvault.service.ProjectService.validateTransferObject(ProjectService.java:450)
      at com.projectvault.servlet.AddEditProjectServlet.doProcess(AddEditProjectServlet.java:176)
      at com.projectvault.servlet.AbstractServlet.execute(AbstractServlet.java:95)
      at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
      at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
      at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
      at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
      at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
      at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
      at java.lang.Thread.run(Thread.java:595)
      15:07:00,816 INFO [STDOUT] Entering.........validateTransferObject
      15:07:00,816 ERROR [LazyInitializationException] failed to lazily initialize a collection of role: com.projectvault.ejb.project.ProjectObject.projectFolderObjects, no session or session was closed
      org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.projectvault.ejb.project.ProjectObject.projectFolderObjects, no session or session was closed
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
      at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
      at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
      at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
      at org.hibernate.collection.PersistentBag.toString(PersistentBag.java:459)
      at com.projectvault.to.ProjectTO.toString(ProjectTO.java:388)
      at java.lang.String.valueOf(String.java:2615)
      at java.lang.StringBuilder.append(StringBuilder.java:116)
      at com.projectvault.service.ProjectService.validateTransferObject(ProjectService.java:454)
      at com.projectvault.servlet.AddEditProjectServlet.doProcess(AddEditProjectServlet.java:176)
      at com.projectvault.servlet.AbstractServlet.execute(AbstractServlet.java:95)
      at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
      at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
      at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
      at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
      at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
      at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
      at java.lang.Thread.run(Thread.java:595)


      can any help this problem

      thanks

        • 1. Re: failed to lazily initialize a collection of role:
          Wolfgang Knauf Master

          Hi !

          Probably you want to access a relationship property when the entity bean is no longer under control of the entity manager (a "detached" entity).

          There are two ways around this problem:
          a) set the fetch type to "EAGER"

          @OneToMany(mappedBy="...", fetch=FetchType.EAGER)
          public Collection<MyChild> getChilds()

          This causes the entity manager to load the child collection when the parent is loaded. May be a big performance problem.

          b) prefetch your childs when the entity bean is still under entity manager control.
          Imagine a find method of a session bean:
          public MyParent findById (Integer id)
          {
           MyParent parent = this.entityManager.find(MyParent.class, id);
           parent.getChilds().size();
          }

          "parent.getChilds().size();" forces loading of the childen.

          Hope this helps

          Wolfgang

          • 2. Re: failed to lazily initialize a collection of role:
            Waseem Quraishi Newbie

            One thing I discovered is if you override the toString() method and output the relationships, it'll force the container to load the relationship related fields. I'm thinking it accomplishes the same thing as fetchtype.eager but i've had more luck with this. Plus it works dual fold since I use the toString() method in conjunction with facesMessages to display what the object coming back is.

            • 3. Re: failed to lazily initialize a collection of role:
              kangjw kangjw Newbie

              for the limitation of only one or zero relation can set fetchtype as eager.so in some case, fetch=FetchType.EAGER is useful. but I have try to invoke getXXXXX() within the session, it still throw the same exception.
              At it happens, I want use system out to see the result just like System.out.println(getXXXX()), and run my test case again,oh my god ,it passed. what happen? I then try to call getXXXX().toString(), it still work.

              Would anybody tell me what it is going on. thank you?

              • 4. Re: failed to lazily initialize a collection of role:
                Wolfgang Knauf Master

                Hi,

                I assume that "getXXX()" is the relationship getter?

                "getXXX().toString()" will probably output only the class name of the relationship list wrapper, but it will not force loading of the content. So you must do something so that the content is loaded, e.g. "getXXX().size().toString()"

                Hope this helps

                Wolfgang

                • 5. Re: failed to lazily initialize a collection of role:
                  Avor Nadal Newbie

                  Wow, what a chance! Today, 8th May of 2009, I've found this thread in Google but was doubting about posting here because of the age of the messages. However I've realized that you've taken it back to life just a few hours ago, ha ha ha. So it's an excellent moment to ask :) .

                  I'm still a beginner with EJB, JBoss and many of the J2EE features, so I have many doubts and much to learn yet. One of my "Achilles heels" has always been this error and its meaning. Thanks to your explanation, Wolfgang, I've been able to understand and prevent it.

                  My problem was that I tried to recover collections when the entity manager had lost any control over the entity. For example, I did it in a different method of my session bean than the one which retrieved the entity. And thus... The mentioned exception was triggered.

                  My question is the following one: How long does the control of the entity manager over the entity last? Only during the execution of the method in which the entity manager retrieved that entity?

                  Again, thank you very much Wolfgang and the rest of people who helps us, the beginners :D .

                  • 6. Re: failed to lazily initialize a collection of role:
                    Brian Cowdery Newbie

                    Generally, an Entity bean is maintained in an "attached" state as long as the transaction is active. Since most implicit transactions begin and end with an the EJB method call your entity becomes "detached" once the invoked EJB method reaches its end. This means you should do all your lazy loading when you fetch the object.

                    For example:

                    @Stateless
                    public class MyDAO {
                     @PersistenceContext
                     EntityManager em;
                    
                     // transaction begins
                     public List<Entity> fetchEntity(Long id) {
                     List<Entity> results = em.createQuery("select e from Entity where e.id = :id").setParameter("id", 1L).getResultList();
                    
                     // lazy load something from retrieved entity
                    
                     return results;
                     }
                     // transaction ends
                    }
                    


                    You should be able to stretch things out if your willing to do your own transaction management - however I'm very fuzzy on this issue so i'm probably not the best person to ask.

                    If your using a Stateful Session Bean, you can go with an Extended Persistence Context (@PersistenceContext(type = PersistenceContextType.EXTENDED)), which provides an session scoped EntityManager allowing you to maintain attached entities across a session - but again, this depends on the transaction in play, and the entity will become detached when the transaction ends.

                    Another consideration is Serialization. If your in a clustered environment, you'll find that the serialization/de-serialization of entities across servers (called passivation & activation) can also detatch your entities. So even if you have a Stateful Session Bean and an extended persistence context - you can still get the LazyInitializationExeption between requests.

                    Some newer frameworks can help you out here as well. Seam provides a "Conversation Scoped EntityManager" which can span multiple request/response cyles (so you rarely have a detached entity). Seam also handles clustering and the serialization/serialization of entities in your session and conversation scopes - so you don't have to worry about serialization detaching your entities either.

                    Spring provides an OpenEntityManagerInView filter which provides similar functionality - although I don't believe it works between requests. I believe Struts2 has a plug-in to provide similar functionality.


                    I hope all this helps, and that i didn't screw things up too badly (someone please correct me if i did :P).


                    • 7. Re: failed to lazily initialize a collection of role:
                      Avor Nadal Newbie

                      bcowdery: First of all excuse my delay to answer you, but I thought that I had already done it. I'm sorry for that ;) .

                      Your explanation is very interesting to me. I'm using Stateless Session Beans in a very "little" environment (compared to a clustered one) so many of the concepts which you mentioned still are a little unfamiliar to me (I'm a rookie yet :P ). However, I'm gonna save a copy of this message for future reference. I'm sure that it will be really useful.

                      The first part of the explanation has solved all my doubts. Basically I'll try to avoid to use that kind of "lazy" operations out of the method which I use to retrieve the desired entity. Indeed I'm already applying that methodology and it's working very well :) .

                      Again, thank you very much for spending your time in helping me ;) .