Could not obtain transaction-synchronized Session for current thread 解決辦法


在整合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包。

問題解決。

 


免責聲明!

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



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