Could not open Hibernate Session for transaction;

這幾天用搭建了一個騰訊雲服務器,將本身的項目放了上去,實現了域名直接訪問,可是卻出現了下面這種錯誤:java

type Exception report

message Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin failed:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin failed: 
    org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:596)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
    org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:334)

大致意思就是使用jdbc出現錯誤,茫然啊,本身在本地電腦上面作的時候可沒出現過這種狀況啊。不過還沒等我仔細思索怎麼解決的時候,看到了錯誤提示裏面的這句話:mysql

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 50,955,266 milliseconds ago.  The last packet sent successfully to the server was 50,955,266 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

第一次看到程序報錯以後,本身之處解決方法的,直接告訴你「wait_timeout」,等待鏈接超時,「or using the Connector/J connection property ‘autoReconnect=true’ to avoid this problem.」。用「autoReconnect=true」就能解決,不過我仍是百度了一下,大神果真多,原來是mysql超時設置的問題,如 果鏈接閒置8小時 (8小時內沒有進行數據庫操做), mysql就會自動斷開鏈接, 要重啓tomcat。同時也 給出了不少方法,在此轉上:
第一種:給jdbc url 增長 autoReconnect=true spring

<property name="url" value="jdbc:mysql://localhost/數據庫實例名稱?&useUnicode=true&characterEncoding=utf-8&autoReconnect=true"/>

第二種:尋找支持重連的鏈接池
附c3p0參數:
idleConnectionTestPeriod 設置空閒鏈接測試周期
preferredTestQuery : 設置一查詢語句,用於重連測試
testConnectionOnCheckin設置爲true
testConnectionOnCheckout設置爲true
第三種:在sessionFactory裏配置(本人使用的是SSH)sql

<property name="hibernateProperties">
   <props>
        <prop key="hibernate.autoReconnect">true</prop>
  </props>
</property>

也可單獨在hibernate.cfg.xml中配置以下:數據庫

<property name="connection.autoReconnect">true</property>
    <property                      name="connection.autoReconnectForPools">true
    </property>
        <property name="connection.is-connection-validation-required">true</property>
相關文章
相關標籤/搜索