---
title: "Cannot get a connection, pool error Timeout waiting for idle object"
author: "mywebcode"
date: "2014-04-17T14:01:00Z"
tags: []
slug: "cannot-get-a-connection-pool-error-timeout-waiting-for-idle-object"
draft: false
lastmod: "2014-04-30T09:15:49Z"
id: 2058298
url: "https://mywebcode.iteye.com/blog/2058298"
---

### 使用Spring的HibernateDaoSupport时的getSession()3个方法的区别

### 在继承了HibernateDaoSupport的Dao中，有三种方式获取session，三种方式的区别是什么，一直很困扰，近期工作不是很忙，就查了一下。

### this.getsession this.getHibernateTemplate().getSessionFactory().getCurrentSession() this.getHibernateTemplate().getSessionFactory().OpenSession 以上三种方式的区别如下： （1） this.getsession实际上是调用了父类HibernateDaoSupport中的方法获得session。使用spring管理hibernate的SessionFactory的时候，这个方法会从session池中拿出一session。这样做有可能有问题，尽管这种方式拿到的Session会自动关闭，但是他是有一定的失效策略的，而且在超session池连接数的时候，spring无法自动的关闭这些session。不推荐使用 （2） this.getHibernateTemplate().getSessionFactory().getCurrentSession()从spring管理的sessionFactory中创建一个绑定线程的session。Spring会根据该线程的执行情况来自动判断是关闭session还是延迟关闭。这样做可以避免手动的管理实务，同时一个线程最多开启和关闭一次session又可以提高程序的性能。 极力推荐使用这种方法 （3） this.getHibernateTemplate().getSessionFactory().OpenSession。这种方法从spring管理的sessionFactory中创建一个session，此session不是线程绑定的。当执行完一个实务的时候自动关闭session。这种方法不用手动管理实务，但是同一个线程多次的开启和关闭session，浪费系统资源和影响执行效率，正常情况下还是不要用了。 ------------------------------------------------------------------------------------------------------------------------------------------------------------------- 另外根据前几次编程试验，发现如果DAO中继承了HibernateDaoSupport的Dao，且采用注解方式，将SessionFactory注入到DAO中，以下两种方式获取session是没有区别的，是一样的，两种方式如下： this.getHibernateTemplate().getSessionFactory().getCurrentSession() 和this.getSessionFactory().getCurrentSession() ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 如果DAO中不继承了HibernateDaoSupport的Dao，且采用注解方式，将SessionFactory注入到DAO中， 则DAO中获取session的方式如下： @Resource private SessionFactory factory; factory.getCurrentSession();

this.getHibernateTemplate().getSessionFactory().getCurrentSession()是不用手动关闭的，交给spring的事物去管理就好！

SessionFactory.openSession() always opens a new session that you have to close once you aredone with the operations. SessionFactory.getCurrentSession() returns a session bound to acontext - you don't need to close this.

本人项目中一开始一些都是使用this.getHibernateTemplate().getSessionFactory().OpenSession后来老是报错Cannot get a connection, pool error Timeout waiting for idle object 后来换成this.getHibernateTemplate().getSessionFactory().getCurrentSession()。当然这种连接池报错的原因很多种，需要自己在工作中慢慢累积吧。