Spring整合hibernate,session什么时候关闭

本文探讨了在Spring整合Hibernate时,如何通过hibernate.current_session_context_class属性设置Open Session in View模式,该模式确保在HTTP请求期间使用同一个Hibernate Session。介绍了Open Session in View的作用,即允许在整个请求过程中进行懒加载数据。同时讨论了singleSession=false的情况,以及OpenSessionInViewFilter的默认行为——不自动flush并设为flush mode never,这可能导致在请求中获取到的不是数据库的最新数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<bean id="sessionFactory_hotelbeds" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource_hotelbeds" />
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.hbm2ddl_auto">${hibernate.hbm2ddl_auto}</prop>
				<prop key="hibernate.dialect">${hibernate.dialect.oracle}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
			</props>
		</property>
	</bean>

hibernate.current_session_context_class的属性值为:org.springframework.orm.hibernate4.SpringSessionContext,由spring来管理session。

<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>

说明一下Open Session in View的作用,就是允许在每次的整个request的过程中使用同一个hibernate session,可以在这个request任何时期lazy loading数据。 
如果是singleSession=false的话,就不会在每次的整个request的过程中使用同一个hibernate session,而是每个数据访问都会产生各自的seesion,等于没有Open Session in View. 
OpenSessionInViewFilter默认是不会对session 进行flush的,并且flush mode 是 never 。

这会出现,在一次请求中,先后调用了service方法A,service方法B,在这两个方法中,是同一个session。如果方法A修改了一条数据,那么在方法B中去查询这条数据,并不是从数据库中查询的,而是从session缓存中取的,因此取到的不是最新数据(取到的是修改之前的数据)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值