使用SpringMVC+OpenJPA开发 WEB应用的过程中将逻辑处理放在了Service层,事务也仅在这个部分开启。但是发现@ManyToOne(fetch = FetchType.LAZY)无法正常使用,显然是因为事务的原因。解决方法就是使用org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor,Google出的资料也非常少例如http://blog.youkuaiyun.com/joolu/archive/2009/07/09/4333499.aspx ,但都没有给出注解方式配置SpringMVC时的解决方法。我的解决方法如下:
<mvc:annotation-driven />
<mvc:interceptors>
<!-- 解决延迟加载 -->
<bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
<property name="entityManagerFactory">
<ref bean="entityManagerFactory"/>
</property>
</bean>
</mvc:interceptors>
当然这个方法虽然完全解决了延迟加载的问题,但其效率还是有一定的牺牲。如果对效率敏感的话可以考虑在Controller层开启事务。
本文介绍如何通过配置OpenEntityManagerInViewInterceptor解决SpringMVC+OpenJPA项目中的@ManyToOne懒加载失效问题,并探讨了可能对性能的影响。
3316

被折叠的 条评论
为什么被折叠?



