轉載自 http://blog.csdn.net/flyjiangs/article/details/51537381android
最近幾年一直再搞android,最近閒下來了,順便玩一下web。web
整了個最新版本的SSH(hibernate5.1.0+spring4.2.6+struts-2.5)spring
在寫dao實現類的時候碰到一個問題,session
@Repository public class UserDaoImpl implements IUserDao { @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } ... }
用了sessionFactory.getCurrentSession()這個以後,會提示app
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 這個異常。(聽說hibernate 4以上的版本纔會有)spa
這裏能夠用Session session = sessionFactory.openSession(),而後代碼中去關閉 session.close.固然爲了偷懶的原則.net
必須不本身去管理session。讓Spring容器本身去處理。hibernate
研究了一下。發現 只要在code
applicationContext.xml 中追加orm
<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/>
而後再在實現類加上@Transactional
@Repository @Transactional public class UserDaoImpl implements IUserDao { @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } ... }
這樣問題就完美解決了。