spring data jpa使用懒操作

如果model对象的某属性使用lazy load,调用这个属性时会报错, failed to lazily initialize a collection of role could not initialize proxy - no Session

查了一圈,得到两个方案

a)     放弃懒操作,改lazy为eager

       可是,如果我只需要一个姓名,却把人的家谱都翻出来了,很浪费很无效啊。

b)     使用OpenSessionInViewFilter

       配置的时候,发现不能用,因为他需要sessionfactory的bean名,而Spring Data JPA把它封装到entityManagerFactory 里了……

但是,这个框架应该会给出对应的过滤器吧~

嗯, OpenEntityManagerInViewFilter 浮出水面,亲测not working

捯饬了好久好久,找到一篇讨论

看到末尾,楼主说:At the moment I give up, I cannot spend more time on this...心声啊~~

讨论中有人建议使用openEntityManagerInViewInterceptor

于是,终于写正文了。

1.      先定义bean

      

<bean name="openEntityManagerInViewInterceptor"

2    class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
3         <property name="entityManagerFactory">
4             <ref bean="entityManagerFactory" />
5         </property>
6     </bean>

2.      为这个默认的注解处理映射加入拦截器bean以自动生成会话

1 <bean
2         class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
3         <property name="interceptors">
4             <list>
5                 <ref bean="openEntityManagerInViewInterceptor" />
6             </list>
7 </property>   
8         </bean> 

 

3.      加入事务

 

使用一个东西却无效的时候,要去看文档,了解它有哪些属性啊,才更可能看出自己的纰漏。不能死盯着错误查,一直待在死胡同里。

若使用@Response ,记得给相应的集合加@JsonIgnore,不然会因为死循环而崩溃的~

 一定要用过滤器可以参考

http://20365.cn/article/17

或许有帮助(有反馈就好了 

 

原文地址:https://www.cnblogs.com/imirror707/p/openEntityManagerInViewInterceptor.html