Spring中使用Session出现Could not obtain transaction-synchronized Session for current thread

又是郁闷的一天,在使用Spring和Hibernate结合的时候竟然发现了这样的错误。
Could not obtain transaction-synchronized Session for current thread
在这里插入图片描述
具体的报错的代码如下,应该是这个getCurrentSession方法的问题

Query query = this.sessionFactory.getCurrentSession().createQuery("from User");

是由于getCurrentSession获取的就这一个Session,大家共用这个Session,也就因此产生了问题。
解决办法:
使用openSession代替getCurrentSession

Query query = this.sessionFactory.openSession().createQuery("from User");

或者查看是否有配置出错
1、Spring中使用Hibernate并且想要使用getCurrentSession一定要在web.xml文件中配置,一定要配置清楚,博主就是吃了这个亏了

 <!-- Spring和Hibernate使用到的过滤器 -->
  <filter>
  	<filter-name>openSessionInView</filter-name>
  	<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
   <filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

2、指定事务管理器

<!-- 事务 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

3、这句话也尽量不要加
因为在Spring事务管理中,currentSession是绑定到SpringSessionContext中的,而不是ThreadLocalSessionContext中的,有可能会出现问题
在这里插入图片描述

<prop key="current_session_context_class">thread</prop>

那么openSession和getCurrentSession的区别有什么呢?
1、openSession,是打开Session,需要手动关闭,每次都是建立一个新的Session
2、getCurrentSession,是获取当前的这个Session,大家共用一个Session,不需要手动关闭,事务执行完成后便自动关闭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值