1

我想使用OpenEntityManagerInViewFilter能夠避免lazyinitialization加載。這是我的web.xml配置:如何配置OpenEntityManagerInViewFilter Spring MVC

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value> 
     WEB-INF/mvc-dispatcher-servlet.xml 
    </param-value> 

</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<filter> 
    <filter-name>hibernateFilter</filter-name> 
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> 
</filter> 

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

我仍然得到exeption:

Servlet.service()對servlet的[mvc-dispatcher]與路徑方面[/ ...]拋出異常

Request processing failed; nested exception is 
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ..., could not initialize proxy - no Session] with root cause 
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ...., could not initialize proxy - no Session 

有人知道我做錯了什麼?

回答

0

原來,因爲我已經配置了我的contextConfigLocation這樣的:

<context-param> 
<param-name>contextConfigLocation</param-name> 
<param-value> 
    WEB-INF/mvc-dispatcher-servlet.xml 
</param-value> 

調度的servlet不一樣的ApplicationContext,並且,它被加載兩次類的東西,因此該解決方案是
1 。創建一個applicationContext.xml, 2.然後將entitymanager bean從mvc dispatcher移到applicationContext.xml。 3.我的web.xml現在看起來像這樣:

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<filter> 
    <filter-name>oemInViewFilter</filter-name> 
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> 
    <init-param> 
     <param-name>entityManagerFactoryBeanName</param-name> 
     <param-value>entityManagerFactory</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>oemInViewFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
    <dispatcher>REQUEST</dispatcher> 
</filter-mapping>