非Spring Boot的Spring项目:OSIV默认值是多少?如何配置?
Spring MVC中OSIV的默认值与配置方式
一、默认值
Spring MVC(非Spring Boot)项目中,OSIV(Open Session in View)的默认值是false,这和Spring Boot默认开启(true)的行为不同。
二、正确配置方式
OSIV是Spring提供的Web层扩展能力,并非JPA原生属性,不能通过jpaProperties配置,需要通过Spring的过滤器或拦截器来开启:
1. Web.xml配置过滤器(推荐)
在项目的web.xml中添加以下配置:
<filter> <filter-name>openEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> <!-- 可选:如果存在多个EntityManagerFactory,指定要关联的bean名称 --> <init-param> <param-name>entityManagerFactoryBeanName</param-name> <param-value>entityManagerFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. Spring Context.xml配置拦截器
如果使用Spring MVC的拦截器方式,在context.xml中添加:
<mvc:interceptors> <bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> </mvc:interceptors>
三、之前配置不生效的原因
你尝试在LocalContainerEntityManagerFactoryBean的jpaProperties中设置jpa.open-in-view,这个配置是Spring Boot封装的简化配置项,仅在Spring Boot环境下生效。在原生Spring MVC中,OSIV由Spring Web层的过滤器/拦截器控制,不属于JPA provider的配置范畴,因此直接配置JPA属性不会起作用。
内容的提问来源于stack exchange,提问作者choding
相关产品推荐
相关产品推荐

