您的位置:首页 > 大数据 > 人工智能

openSession出错:蓝萝卜blu Hibernate4中使用getCurrentSession报Could not obtain transaction-synchronized Sessio

2017-12-12 11:17 274 查看
架个spring4+hibernate4的demo,dao层直接注入的sessionFactory,然后用getCurrentSession方法获取session,然后问题来了,直接报错:

Could not obtain transaction-synchronized Session for current thread


提示无法获取当前线程的事务同步session,略微奇怪,这和事务有什么关系..然后百度一下有人说改成用openSession方法就好了,那我又百度了一下这2个方法的区别:

(1)openSession每次打开都是新的Session,所以多次获取的Session实例是不同的,并且需要人为的调用close方法进行Session关闭。
(2)getCurrentSession是从当前上下文中获取Session并且会绑定到当前线程,第一次调用时会创建一个Session实例,如果该Session未关闭,后续多次获取的是同一个Session实例;事务提交或者回滚时会自动关闭Sesison,无需人工关闭。


看起来这个getCurrentSession方法的确和事务有点关系.然后我加上事务:

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
解决的方式是打开session在web.xml中进行配置:
<!-- 解决 org.hibernate.HibernateException:
Could not obtain transaction-synchronized Session for current 出错问题,主要问题是获取当前线程的问题获取不到 -->
<filter>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
为什么会在测试的时候出现这个问题
因为我们在写代码的时候逻辑的线程是在serviceImpl,现在是在DaoImpl中,ServiceImpl和DaoImpl是2个不同的线程在getCurrentSession()中,
getCurrentSession会从上下文中获取session,并且会绑定在当前线程,第一调用的时候会创建一个Session实例,如果Sesssion未关闭的时候,后续
多次获取的时同一个Session,当事物开启关闭或者回滚的时候就会自动关闭Session,无需手动关闭。
使用openSessionView需要手动关闭。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: