在Spring MVC中使用Spring JPA的时候出现这个错误:LazyInitializationException: could not initialize proxy no session,我的用法是在class中用到了fetch=FetchType.LAZY,这个错误的原因是说:当尝试去取Lazy load的属性时却发现Hibernate Session已经关闭,所以报这个错误。我是使用的Spring data,因此不需要直接操作hibernate相关class. 更详细的解释参见:http://stackoverflow.com/questions/16773506/understanding-spring-mvc-configuration and http://www.codedata.com.tw/java/hibernate-lazy-loading/ 。
我的处理方式是:在srping mvc配置文件中多配置一个filter, 在此filter的生命周期中打开hibernate session。如下:
<!-- for JPA Hibernate problem: LazyInitializationException: could not initialize proxy no session,
see: http://stackoverflow.com/questions/16773506/understanding-spring-mvc-configuration
and http://www.codedata.com.tw/java/hibernate-lazy-loading/
entityManagerFactory is defined in ApplicationContext.xml
Note: if no this hibernate interceptor, lazy load object in Controller will fail -->
<mvc:interceptors>
<bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
<property name="entityManagerFactory">
<ref bean="entityManagerFactory" />
</property>
</bean>
</mvc:interceptors>
这样做在Controller中的lazy load是没错误了,但是如果在其他的模块中调用还可能出错,例如:我在spring security中的UserDetailsService的实现类中报错了,因此我添加了 @Transactional注解。
// if not add @Transactional, all httpFilter call this method will fail. could not initialize proxy - no Session
// see also: http://stackoverflow.com/questions/32603250/could-not-write-json-could-not-initialize-proxy-no-session-error
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String email)