日期:2014-05-16  浏览次数:20468 次

spring的getsession方法造成数据库不关闭连接,SPRING SESSION管理机制。
多运行几次数据库连接就满了程序无法继续执行下去。经测试是使用SPRING的getSession()方法获得的连接没有关闭连接。在这里讨论一下SPRING SESSION管理机制。

先看代码:

public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {



public List queryAll() throws Exception {

// TODO Auto-generated method stub

Session session=super.getSession(true);

String hql="from Item as i";

List l=super.getSession().createQuery(hql).list();

return l;

}

}\

其实上面的代码隐藏了一个问题,数据库连接并没有被关闭,所以一直出现以上的问题。

我的解决方法还是静态模式:

public Session session;
public Session getcurrentSession()
{
if(session==null)
session=this.getSession();
return session;
}

Iterator it =this.getcurrentSession().createQuery(hql).list().iterator();

暂时可以解决此问题。。更好的办法还在网上找到一篇文章和大家共享:

这里提供三个解决方案 方案一:

getHibernateTemplate().find(hql);

虽然没有手动关闭数据库连接,但spring已经帮我们关闭了。

方案二:(经测试,此方案比较有效)

设定HibernateTemplate的AllowCreate为True

在spring API 的HibernateDaoSupport中

protected net.sf.hibernate.Session getSession(boolean allowCreate)

Get a Hibernate Session, either from the current transaction or a new one.

public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {



public List queryAll() throws Exception {

// TODO Auto-generated method stub

Session session=super.getSession(true);

String hql="from Item as i";

List l=session.createQuery(hql).list();

try{

return l;

}finally{

session.close();

}

}

}

Spring API:
geSession()是org.springframework.orm.hibernate3.support.HibernateDaoSupport 中的一个方法,
它可以从当前事务或者一个新的事务获得一个hibernate session.
通常使用releaseSession(org.hibernate.Session)方法与getSession()配合。
如果没有绑定线程,releaseSession关闭由这个DAO的SessionFactory创建的Hibernate Session。 
修改后的代码如下:


public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {

public List queryAll() throws Exception {

// TODO Auto-generated method stub

Session session = super.getSession();

String hql = "from Item as i";

List l = session.createQuery(hql).list();

releaseSession(session);



}

}

困扰了几天的问题终于解决了,项目搁浅了好几天了,就是对spring对session的管理不清楚。

以上内容转载:http://blog.sina.com.cn/s/blog_4779b7f50100b040.html

关于getSession()下面有更多讨论:

http://www.javaeye.com/topic/24309

http://www.javaeye.com/post/140793

总的讨论热点就是getSession()要不要手动关闭的问题。

观点:

1.使用getSession()返回session有两种情况。
   a.当前线程有存在session,就直接返回。
   b.当前线程中不存在session就重新创建一个。

如果spring配置了事务,那么session就不必关闭,在事务完成之后将被自动关闭。如果没有参与事务那就要调用session.close()关闭。

2.getSession()拿到的Session无论是否参与事务,Spring都不负责关闭,除非使用OpenSessionInView模式。