Spring JPA Hibernate problem: LazyInitializationException: could not initialize proxy no session

        在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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值