当前位置: 首页 > 知识库问答 >
问题:

LazyInitializationException:无法初始化代理-在Spring和Hibernate中没有会话

黄昊
2023-03-14

堆栈跟踪

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>
<?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>
<?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>

共有1个答案

何灼光
2023-03-14

它看起来像是在启动一个线程(stacktrace很短,没有任何servlet处理代码,并且以run-method开始),然后操作Hibernate加载的对象。由于hibernate将它的会话与执行线程相关联,因此它无法找到与启动的线程相关联的会话。

你应该:

  1. 不启动新线程。或
  2. 在操作对象的线程中加载对象(只将ID从一个线程传递到另一个线程,而不是加载对象)。或
  3. 在将对象传递给操作它们的线程之前完全加载对象。
 类似资料:
  • 我知道我的问题很奇怪,很难理解 我为我的项目创建了一些结构。但每次我都会遇到不同的问题,如<code>无法初始化代理-再次没有会话</code>或<code>不可序列化异常</code>等 我想得到一些建议或帮助。我尝试使用注释< code>transactional,但不知道在哪种情况下应该使用< code > implements Serializable 。当然,我知道如果我想在视图范围内使

  • 问题内容: 我通过服务将dao称为 在岛上,我得到的产品 运行正常,但如果我将dao类更改为 我得到org.hibernate.LazyInitializationException:无法初始化代理- 没有会话。例外发生在我只是在打印产品的视图层中。我不明白为什么在dao方法中在同一行中返回会导致视图层出现异常,但是如果将其保存在引用中然后返回它,效果很好。 问题答案: 这是一个很好的参考,可让您

  • 我有一个LazyInitializationException问题,我不知道如何解决它。 之前的问题是我打电话的时候。getperson=null,但我修复了findProjectEmployeesWithinDates请求获取此人的调用。但当我调用“findProjectEmployeesWithinDates”时,我遇到了一个例外。查找项目员工的代码包括: 所以用debbug我看到: 它位于f

  • 我使用< code>spring-data-jpa与< code > spring-boot(v 2 . 0 . 0 . release),我刚刚在MySQL上写了一个CRUD演示,但是在运行时出现异常,源代码如下: 源码 User.java UserRepository.java 用户服务测试.java 应用程序.yml 例外详细信息 我尝试另一种方法,它可以成功运行。

  • 注意:关于我如何解决这个问题的例子,请看我自己对这个问题的回答。 我在我的Spring MVC 4 Hibernate 4项目中遇到以下异常: org . hibernate . lazyinitializationexception:无法延迟初始化角色集合:com . my site . company . acknowledges,无法初始化代理-无会话 看了很多关于这个问题的其他问题,我明白

  • 问题内容: 我的代码检索与用户有关的所有信息: 在简单地返回一组用户的ES。 我的问题是:即使会话已经关闭,为什么对象仍然具有其值(例如名称)?是该类的实例变量。但是为什么我不能检索其值却可以检索该类的常规实例变量? 是一个。 问题答案: 有关使用惰性关联的hibernate文档清楚地将这种访问称为错误。只有在会话仍处于打开状态时,才能与延迟关联的对象进行交互。文档的该部分还提供了访问对象的延迟关