Results 1 to 8 of 8

Thread: LazyInitializationException with Hibernate

  1. #1

    Default LazyInitializationException with Hibernate

    I know there are a lot of postings on LazyInitializationException, and I've read many of them, but I haven't been able to fix this problem yet.

    I am starting to use Spring and Hibernate 2.1 in a pre-existing web application. I am using the DAO pattern and Karl Baum's Weblog entry "Lazy Initialization and the DAO pattern with Hibernate and Spring". I'm using the Filter method.

    I'm under the impression that this filter will open a hibernate session and keep it open for the duration of the request. The first time the objects are accessed, the session is open. But when I try to get the size of a child collection, I get a LazyInitializationException.

    I also created a subclass of ContextLoaderServlet. In it I override createContextLoader(), where I return an instance of my own subclass of ContextLoader.

    Code:
    public class MyContextLoader extends ContextLoader {
        public MyContextLoader() {
            super();
        }
    
        private static WebApplicationContext myWebApplicationContext = null;
    
        public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
                throws BeansException {
            myWebApplicationContext = super.initWebApplicationContext(servletContext);
            return myWebApplicationContext;
        }
    
        // Allow legacy code the get the instance of the application context so they 
        // can get Spring beans.
        public static WebApplicationContext getMyWebApplicationContext() {
            return myWebApplicationContext;
        }
    }


    I am using the DAO pattern as follows:

    DAO Impl:

    Code:
    public class MyObjectDaoImpl extends HibernateDaoSupport implements
            MyObjectDao {
        /**
         * Retrieves a List of MyObject objects, using the Spring Framework.
         * @return List
         */
        public List getObjects() {
            return getHibernateTemplate().find("from MyObject");
        }
    }
    web.xml:
    Code:
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*&#58;spring-init-servlet.xml</param-value>
      </context-param>
    
      <filter>
        <filter-name>hibernateFilter</filter-name>
        <filter-class>org.springframework.orm.hibernate.support.OpenSessionInViewFilter</filter-class>
      </filter>
    
      <filter-mapping>
        <filter-name>hibernateFilter</filter-name>
        <url-pattern>/servlets/com.company.nav.OurCommandDispatcherServlet</url-pattern>
      </filter-mapping>
    
      <servlet>
        <servlet-name>SpringContextServlet</servlet-name>
        <servlet-class>com.company.springframework.MyContextLoaderServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
    Any help will be greatly appreciated.

    Regards,
    John[/code]

  2. #2

    Default

    Hi,

    your Hibernates' url-pattern is wrong. You need something like *.do, or whatever your URLs look like.

    Simon

  3. #3

    Default

    Quote Originally Posted by simtin
    Hi,

    your Hibernates' url-pattern is wrong. You need something like *.do, or whatever your URLs look like.

    Simon
    Thank you for your reply.

    It looks odd, but I think it's correct. I have set breakpoints in the filter, and they are hit when I expect them to be hit.

    When the code tries to find the size of a child collection, I get the LazyInitializationException. I can see the session is closed.

    Today I tried to use a transaction interceptor, but I still get the same exception.

    Code:
    Tue Aug 30 12&#58;55&#58;07.055 EDT 2005&#58; net.sf.hibernate.LazyInitializationException&#58; Failed to lazily initialize a collection - no session or session was closed
    
    net.sf.hibernate.LazyInitializationException&#58; Failed to lazily initialize a collection - no session or session was closed
    
    	at net.sf.hibernate.collection.PersistentCollection.initialize&#40;PersistentCollection.java&#58;209&#41;
    
    	at net.sf.hibernate.collection.PersistentCollection.read&#40;PersistentCollection.java&#58;71&#41;
    
    	at net.sf.hibernate.collection.Set.size&#40;Set.java&#58;106&#41;
    
    	at com.company.de.client.contract.ContractTableData.setUpRowData&#40;ContractTableData.java&#58;213&#41;
    
    	at com.company.de.cmdarch.ContractExecutor.loadContractsForDisplay&#40;ContractExecutor.java&#58;251&#41;
    
    	at com.company.de.cmdarch.ContractExecutor.execute&#40;ContractExecutor.java&#58;114&#41;
    
    	at sun.reflect.NativeMethodAccessorImpl.invoke0&#40;Native Method&#41;
    
    	at sun.reflect.NativeMethodAccessorImpl.invoke&#40;NativeMethodAccessorImpl.java&#58;39&#41;
    
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke&#40;DelegatingMethodAccessorImpl.java&#58;25&#41;
    
    	at java.lang.reflect.Method.invoke&#40;Method.java&#58;324&#41;
    
    	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection&#40;AopUtils.java&#58;288&#41;
    
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint&#40;ReflectiveMethodInvocation.java&#58;155&#41;
    
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed&#40;ReflectiveMethodInvocation.java&#58;122&#41;
    
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke&#40;TransactionInterceptor.java&#58;57&#41;
    
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed&#40;ReflectiveMethodInvocation.java&#58;144&#41;
    
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke&#40;JdkDynamicAopProxy.java&#58;174&#41;
    
    	at $Proxy10.execute&#40;Unknown Source&#41;
    
    	at com.company.cmdarch.server.CommandDispatcher.dispatch&#40;CommandDispatcher.java&#58;146&#41;
    
    	at com.company.cmdarch.transport.server.http.TransportServlet.service&#40;TransportServlet.java&#58;72&#41;
    
    	at javax.servlet.http.HttpServlet.service&#40;HttpServlet.java&#58;853&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run&#40;ServletStubImpl.java&#58;1006&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;419&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;315&#41;
    
    	at weblogic.servlet.ServletServlet.service&#40;ServletServlet.java&#58;47&#41;
    
    	at javax.servlet.http.HttpServlet.service&#40;HttpServlet.java&#58;853&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run&#40;ServletStubImpl.java&#58;1006&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;419&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;315&#41;
    
    	at weblogic.servlet.internal.RequestDispatcherImpl.forward&#40;RequestDispatcherImpl.java&#58;328&#41;
    
    	at com.company.nav.MainCtrl.service&#40;MainCtrl.java&#58;137&#41;
    
    	at javax.servlet.http.HttpServlet.service&#40;HttpServlet.java&#58;853&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run&#40;ServletStubImpl.java&#58;1006&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;419&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;315&#41;
    
    	at weblogic.servlet.ServletServlet.service&#40;ServletServlet.java&#58;47&#41;
    
    	at javax.servlet.http.HttpServlet.service&#40;HttpServlet.java&#58;853&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run&#40;ServletStubImpl.java&#58;1006&#41;
    
    	at weblogic.servlet.internal.ServletStubImpl.invokeServlet&#40;ServletStubImpl.java&#58;419&#41;
    
    	at weblogic.servlet.internal.TailFilter.doFilter&#40;TailFilter.java&#58;28&#41;
    
    	at weblogic.servlet.internal.FilterChainImpl.doFilter&#40;FilterChainImpl.java&#58;27&#41;
    
    	at org.springframework.orm.hibernate.support.OpenSessionInViewFilter.doFilterInternal&#40;OpenSessionInViewFilter.java&#58;172&#41;
    
    	at org.springframework.web.filter.OncePerRequestFilter.doFilter&#40;OncePerRequestFilter.java&#58;76&#41;
    
    	at weblogic.servlet.internal.FilterChainImpl.doFilter&#40;FilterChainImpl.java&#58;27&#41;
    
    	at com.company.nav.RequestMonitor.doFilter&#40;RequestMonitor.java&#58;47&#41;
    
    	at weblogic.servlet.internal.FilterChainImpl.doFilter&#40;FilterChainImpl.java&#58;27&#41;
    
    	at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run&#40;WebAppServletContext.java&#58;6724&#41;
    
    	at weblogic.security.acl.internal.AuthenticatedSubject.doAs&#40;AuthenticatedSubject.java&#58;321&#41;
    
    	at weblogic.security.service.SecurityManager.runAs&#40;SecurityManager.java&#58;121&#41;
    
    	at weblogic.servlet.internal.WebAppServletContext.invokeServlet&#40;WebAppServletContext.java&#58;3764&#41;
    
    	at weblogic.servlet.internal.ServletRequestImpl.execute&#40;ServletRequestImpl.java&#58;2644&#41;
    
    	at weblogic.kernel.ExecuteThread.execute&#40;ExecuteThread.java&#58;219&#41;
    
    	at weblogic.kernel.ExecuteThread.run&#40;ExecuteThread.java&#58;178&#41;
    Regards,
    John

  4. #4
    Join Date
    Aug 2005
    Posts
    3

    Default

    I'm having the exact same problem. The first call works fine. I'm getting my collection, but then when I try to get a child entry, the exception is thrown saying my session is closed.

  5. #5
    Join Date
    Aug 2005
    Posts
    3

    Default

    Actually, a friend and I just fixed it.

    Check for this in your code:

    web.xml:
    Code:
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>
    		classpath&#58;applicationContext.xml
    		classpath&#58;applicationContext-acegi-security.xml
    	</param-value>
    </context-param>
    struts-config.xml:
    Code:
    <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
    	<set-property property="contextConfigLocation"
    		value="/WEB-INF/conf/admin/action-servlet.xml" />
    </plug-in>
    MAKE SURE that your applicationContext is NOT in both places. This is what was causing my problem. Your Session Factory can only be loaded once, and yours might be loading multiple times somewhere in your code. It took us about 3 1/2 hours to find this, so you might want to do a full-text search of your code just in case.

  6. #6

    Default

    Quote Originally Posted by karlshea
    Your Session Factory can only be loaded once, and yours might be loading multiple times somewhere in your code.
    Sure enough, it's loading twice. When I have this in, it loads twice; when I take it out, it doesn't load at all:

    Code:
    <servlet> 
        <servlet-name>SpringContextServlet</servlet-name> 
        <servlet-class>com.company.springframework.MyContextLoaderServlet</servlet-class> 
        <load-on-startup>1</load-on-startup> 
      </servlet>
    I don't know why.

    Regards,
    John

  7. #7
    Join Date
    Aug 2005
    Posts
    3

    Default

    Check to see if your spring-init-servlet.xml has a double definition, or if another file is loading that specifies spring-init-servlet.xml again.

  8. #8

    Default

    Quote Originally Posted by karlshea
    Check to see if your spring-init-servlet.xml has a double definition, or if another file is loading that specifies spring-init-servlet.xml again.
    I checked this out with a second set of eyes, and that's not it.

    I don't know what was causing it to get run twice, but someone sat through a debugging session with me and saw I was overriding a method that initializes the context, and suggested a workaround: don't initialize it twice.

    Here's what I did, but I don't like it. If anyone has encountered this before and knows what's really happening, I'm all ears.

    Code:
    package com;
    
    import org.springframework.web.context.*;
    import org.springframework.beans.BeansException;
    import javax.servlet.ServletContext;
    
    public class TxContextLoader extends ContextLoader &#123;
        public TxContextLoader&#40;&#41; &#123;
            super&#40;&#41;;
        &#125;
    
        private static WebApplicationContext txWebApplicationContext = null;
    
        /**
         * Override this method to save the ApplicationContext somewhere static so 
         * our non-spring-instantiated code can load Spring classes.
         */
        public WebApplicationContext initWebApplicationContext&#40;ServletContext servletContext&#41;
                throws BeansException &#123;
            //
            // Here is the workaround&#58; Only do it once
            //
            if&#40;getTxWebApplicationContext&#40;&#41; == null &#41; &#123;
                txWebApplicationContext = super.initWebApplicationContext&#40;
                        servletContext&#41;;
            &#125;
            return txWebApplicationContext;
    
        &#125;
    
        /**
         * Access for non-spring-loaded classes
         */
        public static WebApplicationContext getTxWebApplicationContext&#40;&#41; &#123;
            return txWebApplicationContext;
        &#125;
    &#125;
    Code:
    package com;
    
    import org.springframework.web.context.*;
    
    public class TxContextLoaderServlet extends ContextLoaderServlet &#123;
        public TxContextLoaderServlet&#40;&#41; &#123;
            super&#40;&#41;;
        &#125;
    
        protected ContextLoader createContextLoader&#40;&#41; &#123;
                return new TxContextLoader&#40;&#41;;
        &#125;
    &#125;
    Thank you for your time.

    Regards,
    John

Similar Threads

  1. Replies: 5
    Last Post: Dec 27th, 2005, 07:00 AM
  2. Loosing my SecureContext
    By sklakken in forum Security
    Replies: 3
    Last Post: Jul 21st, 2005, 01:44 PM
  3. Replies: 3
    Last Post: Nov 19th, 2004, 07:16 PM
  4. Replies: 9
    Last Post: Sep 25th, 2004, 12:35 PM
  5. Replies: 7
    Last Post: Aug 21st, 2004, 03:42 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •