java.sql.SQLException: Io 异常: Connection refused错误的一种可能原因

在使用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;
	}
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值