Could not open Hibernate Session for transaction;

这几天用搭建了一个腾讯云服务器,将自己的项目放了上去,实现了域名直接访问,但是却出现了下面这种错误:

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出现错误,茫然啊,自己在本地电脑上面做的时候可没出现过这种情况啊。不过还没等我仔细思索怎么解决的时候,看到了错误提示里面的这句话:

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

<property name="url" value="jdbc:mysql://localhost/数据库实例名称?&useUnicode=true&characterEncoding=utf-8&autoReconnect=true"/>

第二种:寻找支持重连的连接池
附c3p0参数:
idleConnectionTestPeriod 设置空闲连接测试周期
preferredTestQuery : 设置一查询语句,用于重连测试
testConnectionOnCheckin设置为true
testConnectionOnCheckout设置为true
第三种:在sessionFactory里配置(本人使用的是SSH)

<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>
posted @ 2016-09-28 17:49  矜持的折返跑  阅读(1404)  评论(0编辑  收藏  举报