又是郁闷的一天,在使用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,不需要手动关闭,事务执行完成后便自动关闭