You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:51:09