关于Hibernate Could not obtain transaction-synchronized Session for current thread

来源:互联网 发布:淘宝女装店招图片 编辑:程序博客网 时间:2024/06/13 17:30

最近几年一直再搞android,最近闲下来了,顺便玩一下web。

整了个最新版本的SSH(hibernate5.1.0+spring4.2.6+struts-2.5)

在写dao实现类的时候碰到一个问题,

@Repositorypublic class UserDaoImpl implements IUserDao {@Autowiredprivate SessionFactory sessionFactory;private Session getSession(){return sessionFactory.getCurrentSession();}...}


用了sessionFactory.getCurrentSession()这个之后,会提示

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 这个异常。(据说hibernate 4以上的版本才会有)

这里可以用Session session = sessionFactory.openSession(),然后代码中去关闭 session.close.当然为了偷懒的原则

必须不自己去管理session。让Spring容器自己去处理。

研究了一下。发现 只要在

applicationContext.xml 中追加

 <!-- 配置事务管理器 -->     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">         <property name="sessionFactory" ref="sessionFactory"></property>     </bean>         <tx:annotation-driven transaction-manager="transactionManager"/>


然后再在实现类加上@Transactional

@Repository@Transactionalpublic class UserDaoImpl implements IUserDao {@Autowiredprivate SessionFactory sessionFactory;private Session getSession(){return sessionFactory.getCurrentSession();}...}


这样问题就完美解决了。


1 0