在使用Hibernate进行数据库处理时,频繁进行数据库操作过程中,时不时会出现java.sql.SQLException: Io 异常: Connection refused的错误,找了网上的资料,都没能解决,最后通过分析源代码,终于找到了问题的症结所在:SessionFactory没有关闭,以下是我修改前的代码:
public class HibernateSupport {
private Session session=null;
public Session getSession(){
try {Configurationconfig=new Configuration().configure();
SessionFactorysessionFactory=config.buildSessionFactory();
session=sessionFactory.openSession();
} catch (HibernateException e) {
e.printStackTrace();
}
return session;
}
public boolean closeSession(){
try {
session.close();
} catch (HibernateException e) {
e.printStackTrace();
return false;
}
return true;
}
}
这意味着每创建一个Session都会增加一个SessionFactory, 而每增加一个SessionFactory实例都要建立一次数据库连接,这样导致的系统中Oracle.exe进程的线程数不断增加,最后的结果是数据库连接被强制关闭,也就是Connection Refused,解决的方法是:将SessionFactory定义为静态变量,让所有的使用SessionFactory的类都共享一个实例,这样就可以避免以上问题的发生,当然也可以在每次关闭Session时关闭SessionFactory,但这样会造成一定的资源浪费。
修改后的代码如下:
public class HibernateSupport {
private static Configuration config=null;
private static SessionFactory sessionFactory=null;
static{
config=new Configuration().configure();
sessionFactory=config.buildSessionFactory();
}
private Session session=null;
public Session getSession(){
try {
session=sessionFactory.openSession();
} catch (HibernateException e) {
e.printStackTrace();
}
return session;
}
public boolean closeSession(){
try {
session.close();
} catch (HibernateException e) {
e.printStackTrace();
return false;
}
return true;
}
}