使用SpringMVC+OpenJPA开发 WEB应用的过程中将逻辑处理放在了Service层,事务也仅在这个部分开启。但是发现@ManyToOne(fetch = FetchType.LAZY)无法正常使用,显然是因为事务的原因。解决方法就是使用org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor,Google出的资料也非常少例如http://blog.csdn.net/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层开启事务。