Search code examples
springhibernatesessionspring-mvclazy-initialization

LazyInitializationException: could not initialize proxy - no Session in Spring and Hibernate


I'm getting this error: "org.hibernate.LazyInitializationException: could not initialize proxy - no Session" in my webapp. I use Spring and Hibernate, and I execute the queries with "sessionFactory.getCurrentSession()".

I read a lot about this problem, so I tried with the answers that I found, but it doesn't work. I'm currently using "OpenSessionInViewFilter" and "OpenSessionInViewInterceptor".

I attach my configuration files.

Thank you in advance.

Stack trace

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at involve.gbi.persistence.entities.Actividad_$$_javassist_33.getDireccion(Actividad_$$_javassist_33.java)
at involve.gbi.cro.business.data.model.HibernateCRODCM.addActividadesToWc(HibernateCRODCM.java:676)
at involve.gbi.cro.business.data.model.HibernateCRODCM.generateWorkingCalendars(HibernateCRODCM.java:370)
at involve.gbi.cro.business.algorithm.CROVisitsAlgorithmPeriodByPeriodDayByDay.setIntervaloOptimizacionActivo(CROVisitsAlgorithmPeriodByPeriodDayByDay.java:126)
at involve.gbi.cro.business.algorithm.CROVisitsAlgorithmPeriodByPeriodDayByDay.run(CROVisitsAlgorithmPeriodByPeriodDayByDay.java:738)

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.2.xsd ">


    <context:annotation-config />
    <context:component-scan base-package="example.gbi" />
    <!-- <context:property-placeholder location="classpath:appConfig.properties,classpath:jdbc.properties" 
        system-properties-mode="OVERRIDE" ignore-unresolvable="true" /> -->
    <!-- <import resource="spring-ws-config.xml"/> -->
    <import resource="database-config.xml" />
    <import resource="application-security.xml"/>

</beans>

application-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">
    <global-method-security secured-annotations="enabled" pre-post-annotations="enabled" />
    <http auto-config="false"  use-expressions="true" disable-url-rewriting="true" create-session="ifRequired">

           <intercept-url pattern="/admin**" access="hasRole('Administrator')" /> 
           <intercept-url pattern="/admin/j_spring_security_check" access="permitAll"/>
          <intercept-url pattern="/admin/login.jsp" access="permitAll" />
          <intercept-url pattern="/admin/logout.jsp" access="permitAll" />
          <intercept-url pattern="/admin/accessdenied.jsp" access="permitAll" />

        <form-login login-page="/admin/login.jsp" login-processing-url="/admin/j_spring_security_check" default-target-url="/admin/api/welcome" authentication-failure-url="/admin/accessdenied.jsp" />
        <logout logout-success-url="/admin/logout.jsp" />
    </http>
    <authentication-manager  erase-credentials="false">
         <authentication-provider user-service-ref="myUserDetailsService" />
    </authentication-manager>

    <beans:bean name="myUserDetailsService" class="security.UserDetailService" />


</beans:beans>

database-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!--    <context:property-placeholder location="classpath:persistence-mysql.properties" /> -->

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="configLocation">
            <value>
                classpath:hibernate.cfg.xml
            </value>
        </property>
    </bean>


    <bean id="txManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />

    <!-- The transaction advice - setting attributes for transactions -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" isolation="SERIALIZABLE" />
            <tx:method name="remove*" propagation="REQUIRED" isolation="SERIALIZABLE" />
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
    <!-- Establish the AOP transaction cross cutting concern and define which classes/methods are transactional  -->
    <aop:config>
        <aop:pointcut id="serviceOperations" expression="execution(* persistence.manager.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperations" />
    </aop:config>



    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

</beans>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
    <session-factory>
        <property name="show_sql">true</property>
        <property name="hibernate.connection.datasource">java:comp/env/jdbc/CRO</property>

        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.jdbc.batch_size">0</property>
        <property name="hibernate.c3p0.min_size">1</property>
        <property name="hibernate.c3p0.max_size">300</property>
        <property name="hibernate.c3p0.acquireIncrement">5</property>
        <property name="hibernate.c3p0.idle_test_period">10</property>
        <property name="hibernate.c3p0.timeout">600</property>
        <property name="hibernate.c3p0.validate">true</property>            
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.use_query_cache">true</property>
        <property name="hibernate.generate_statistics">true</property>

        <property name="configLocation">hibernate.cfg.xml"</property>
        <mapping class="persistence.entities.LocationTrack"/>
        ··· A lot of mappings class ···
        <mapping class="persistence.entities.VisitaHistorico"/>
    </session-factory>
</hibernate-configuration>

mvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"


       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task-3.2.xsd
        ">



    <context:component-scan base-package="example.*" />

      <mvc:annotation-driven>
          <mvc:message-converters register-defaults="true">
              <bean class="web.configuration.GsonHttpMessageConverter" >
              <property name="supportedMediaTypes" value = "application/json;charset=UTF-8" />
              </bean>
          </mvc:message-converters>
      </mvc:annotation-driven>

    <mvc:interceptors>
            <bean class="org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor">
                <property name="sessionFactory">
                    <ref local="sessionFactory"/>
                </property>
            </bean>
        </mvc:interceptors>

    <import resource="applicationContext.xml"/>


    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <task:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/www/" />
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>CROQueryServletTesting</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

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

    <filter-mapping>
        <filter-name>OpenSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>SERVLET-REST</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
      <servlet-name>SERVLET-REST</servlet-name>
      <url-pattern>/admin/api/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SERVLET-REST</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SERVLET-REST</servlet-name>
        <url-pattern>/CROBasicQueryServlet</url-pattern>
    </servlet-mapping>


  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>


    <servlet>
        <description></description>
        <display-name>CROLocationTrackingServlet</display-name>
        <servlet-name>CROLocationTrackingServlet</servlet-name>
        <servlet-class>web.CROLocationTrackingServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CROLocationTrackingServlet</servlet-name>
        <url-pattern>/CROLocationTrackingServlet</url-pattern>
    </servlet-mapping>


</web-app>

Solution

  • It looks like you are starting a thread (the stacktrace is short, doesn't have any servlet handling code and starts with a run-method) and then manipulate objects loaded by hibernate. Since hibernate associates it's sessions to execution threads, it cannot find the session associated with the thread you started.

    You should:

    1. Not start a new thread. Or
    2. Load the objects in the thread that manipulates them (only pass ids from one thread to another, not loaded objects). Or
    3. Load the objects fully before passing the objects to the thread that manipulates them.