在整合springMVC與hibernate時,DAO層在getCurrentSession()時報錯:
HTTP Status 500 - Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
錯誤跟蹤到sessionFactory.getCurrentSession();:
protected Session getCurrentSession() { return this.sessionFactory.getCurrentSession(); }
網上找了幾個解決方案(http://www.cnblogs.com/chyu/p/4817291.html)均未解決。
而后在http://bbs.csdn.net/topics/390971954問答的3樓中看到:
我也遇到過這個問題,我的是在Controller中的掃描路徑錯了,如果在Controller中也掃描了Service,這個時候的Service是沒有事務特性的,所以會報錯。
解決方案就是不要在Controller中掃描事務相關的Service。參考:http://blog.csdn.net/frankcheng5143/article/details/51308344
遂開始檢查掃描路徑,首先web工程的web.xml引入spring-web.xml和springmvc-servlet.xml:
spring-web.xml:
<!-- 掃描路徑,不掃描Controller --> <context:component-scan base-package="casic.bj"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
springmvc-servlet.xml:
<!-- 設置使用注解的類所在的jar包 --> <context:component-scan base-package="casic.bj"></context:component-scan> <!-- 啟用spring mvc 注解 --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:后綴 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean>
其中springmvc-servlet.xml負責掃描controller,而掃描范圍為整個項目路徑,所以將service也一並掃描,導致出現以上錯誤。
解決方法:
修改:
base-package="casic.bj"
為
base-package="casic.bj.controller"
即僅掃描相應controller包。
問題解決。