java mysql hibernate SessionFactory 8 小时数据库连接关闭错误解决方案:

mysql hibernate SessionFactory 8 小时数据库连接关闭错误解决方案:

可以通过SessionFactory获得连接,判断是否关闭,关闭了就重新打开。

 

 

package org.dj.model;

import java.sql.SQLException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

扫描二维码关注公众号,回复: 411695 查看本文章

import org.hibernate.connection.ConnectionProvider;

import org.hibernate.engine.SessionFactoryImplementor;

public class MyHgetSessionFactory {

private static SessionFactory factory = null;

public static synchronized SessionFactory getSessionFactory() {

if (null == factory || factory.isClosed()) {

Configuration cfg = new Configuration().configure();

factory = cfg.buildSessionFactory();

}else{

ConnectionProvider cp = ((SessionFactoryImplementor)factory).getConnectionProvider();

try {

java.sql.Connection con = cp.getConnection();

if(con.isClosed()){

Configuration cfg = new Configuration().configure();

factory = cfg.buildSessionFactory();

}

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

////通过打开session来判断连接是否关闭

//Session session = null;

//try {

//session = factory.openSession();

//factory.get

//if(null == session || session.connection().isClosed()){

//Configuration cfg = new Configuration().configure();

//factory = cfg.buildSessionFactory();

//}

//} catch (Exception e) {

//e.printStackTrace();

//

////重新连接

//Configuration cfg = new Configuration().configure();

//factory = cfg.buildSessionFactory();

//

//} finally {

//if (null != session) {

//if (session.isOpen()) {

//// 关闭session

//session.close();

//}

//}

//}

return factory;

}

}

 

猜你喜欢

转载自mr-lili-1986-163-com.iteye.com/blog/2371374