關於Hibernate Could not obtain transaction-synchronized Session for current thread


轉載自 http://blog.csdn.net/flyjiangs/article/details/51537381

最近幾年一直再搞android,最近閑下來了,順便玩一下web。

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

在寫dao實現類的時候碰到一個問題,

 1 @Repository  
 2 public class UserDaoImpl implements IUserDao {  
 3   
 4     @Autowired  
 5     private SessionFactory sessionFactory;  
 6   
 7     private Session getSession(){  
 8         return sessionFactory.getCurrentSession();  
 9           
10     }  
11     ...   
12 }  

用了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 中追加

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

然后再在實現類加上@Transactional

 1 @Repository  
 2 @Transactional  
 3 public class UserDaoImpl implements IUserDao {  
 4   
 5     @Autowired  
 6     private SessionFactory sessionFactory;  
 7   
 8     private Session getSession(){  
 9         return sessionFactory.getCurrentSession();  
10           
11     }  
12     ...   
13 }  

這樣問題就完美解決了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM