日期:2014-05-19  浏览次数:20682 次

spring集成hibernateTemplate 如何正确获取session

 spring集成了sessionFactory 和hibernatetemplate、

 该如何正确获取到session、

 

 问题来源:

 原来项目的service接口上有事务注解、
 session都是从当前的事务中获取的、
 如:接口上的注解
Java code
@Transactional(propagation = Propagation.REQUIRED,rollbackFor=Exception.class)

 获取的代码:
Java code
 //hibernateTemplate 从spring中获取的、
 SessionFactory sf = hibernateTemplate.getSessionFactory();
 //创建session  、从当前事务中获取session
 Session session = SessionFactoryUtils.getSession(sf, false); //true是找不到事务允许新建个session,false是必须从当前事务中获取
 
//dosomething();

 //释放是这样释放的
 session.clear();
 SessionFactoryUtils.releaseSession(session, sf);


 这以前的做法是肯定不会连接数涨幅的、
 
 因为事务这东西会造成锁表和锁行(mysql -- innoDB)、
 造成了不必要的麻烦、
 老大后来给去掉了、比如查询就不需要事务、

 而这部分获取session的代码就全不行了、而且又是必须拿session来操作dao的、
 具体错误就是 :hibernate认为当前没有事务给分配、而我又强制从当前事务中获取的错误、

 
  
  【现在session获取是能获取到、只不过无论我怎么释放都不能释放、连接数量猛涨、】
  
  现在想问下究竟在这种配置环境下该如何获取和释放session、让连接数稳定在一个范围内、


  我现在的获取方法试了很多种、但是都是猛涨连接数那种的、

 
Java code
 //能获取session的方法我都试了些、
  SessionFactory sf = hibernateTemplate.getSessionFactory();//sf
  Session session =  sf.openSession();//session1
  Session session =  SessionFactoryUtils.getSession(sf,true);//session2
  Session session =  SessionFactoryUtils.getNewSession(sf);//session3
  Session session =  SessionFactoryUtils.doGetSession(sf, true);//session4
  Session session =  sf.getCurrentSession(); //session5

  //do somethin ..
  
  session.clear();


  //无论怎么样关闭,我都无法释放session
  session.close();
  //甚至连这样释放的都一并用上了
  SessionFactoryUtils.closeSession(session);
  SessionFactoryUtils.releaseSession(session, hibernateTemplate.getSessionFactory());  


求解决方案、
 

------解决方案--------------------
LZ这个问题我也出现过,我配置连接池的时候,死活不知道怎么的,数量一下子就没有了。后来才发生在hibernate中去拿都有问题,这个问题,请牛人给解释一下。后来我使用
this.getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException,
SQLException {
return session.createQuery(hql).list();
}
});
这个方式使用了Session,这个就不需要我们去处理,这样叫给容器管理去了
------解决方案--------------------
做成单例。
------解决方案--------------------
ActionContext.getContext().getSession();

有request,也可以通过request 获取 request.getSession()
------解决方案--------------------
继承HibernateDaoSupport 的类,注入了sessionFactory,也可以直接this.getSession()获得
------解决方案--------------------
SessionFactory.openSession().
------解决方案--------------------
SessionFactory.openSession();
------解决方案--------------------
既使用了spring,就可以把对应的dao注入到相应的业务类中,然后就可以用调用dao的操作数据库方法了。

dao的话,把sessionFactory注入进去,然后继承extends HibernateDaoSupport ,调用this.getHibernateTemplate()执行相应的数据库操作。比如查询就是
this.getHibernateTemplate().find()


------解决方案--------------------
建议楼主去我的csdn博客看看我的da