朋友突然发来信息,说部署程序出现了cannot open hibernate session问题,我立马想到了连接数据库出现了问题,也许是session提前关闭还有就是连接出现问题。
异常:
javax.servlet.ServletException: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin failed:
root cause
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.TransactionException: JDBC begin failed:
解决方案:1 检查hibernate配置文件中数据库的用户名和密码
2 jdbc的URL中添加 autoReconnect=true 如:
url="jdbc:mysql://localhost/数据库实例名称?&useUnicode=true&characterEncoding=utf-8&autoReconnect=true";
3 在hibernate配置文件中添加
<props>
<prop key="hibernate.autoReconnect">true</prop>
</props>
4 寻找支持重连的连接池。
注意:c3p0连接池支持重连;重连参数是:
idleConnectionTestPeriod 设置空闲连接测试周期
preferredTestQuery : 设置一查询语句,用于重连测试
testConnectionOnCheckin设置为true
testConnectionOnCheckout设置为true