org.hibernate.SessionException: Session is closed! 异常解决方法
刚刚在程序中出现了org.hibernate.SessionException: Session is closed! 这个异常,查看Firebug控制台,还能发现有这样的异常信息org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction;记录一下解决方法。
程序代码如下:
public boolean activityUpdate(Activity activity) throws Exception { Session session = null; Transaction tran = null; boolean r = false; try{ //创建sql String sql1 = "delete from Activityfilm where activityid=" + activity.getId();//删除活动影片数据 String sql2 = "delete from Activityclient where activityid=" + activity.getId();//删除活动客户数据 //获得session session = this.getSession(); //开始事务 tran = session.beginTransaction(); //执行删除操作 int del_1 = session.createSQLQuery(sql1).executeUpdate(), del_2 = session.createSQLQuery(sql2).executeUpdate(); System.out.println("del_1: "+ del_1 + "###del_2: " + del_2); //更新活动 session.update(activity); if(del_1 > 0 && del_2 > 0){ r = true; }else{ r = false; } System.out.println("r: "+ r); tran.commit(); if(!r){//执行回滚 System.out.println("执行回滚#####################"); tran.rollback(); } }catch(Exception ex){ if(tran != null){ System.out.println("执行回滚@@@@@@@@@@@@@@@@@@@@@"); tran.rollback(); } ex.printStackTrace(); }finally{ if(tran != null){ System.out.println("设置事务为null"); tran = null; } if(session != null){ System.out.println("关闭session$$$$$$$$$$$$$$$$$"); session.close();//执行这一行总是报异常:org.hibernate.SessionException: Session is closed! } } System.out.println("返回: "+ r); return r; }
引用网上的资料:
先看看SessionFactory.getCurrentSession与openSession的区别
1. 如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,也就是不用再session.close()了。但是如果使用的是openSession方法创建的session的话,
那么必须显示的关闭session,也就是调用session.close()方法。这样commit后,session并没有关闭
/*2. getCurrentSession的使用可以参见hibernate\hibernate-3.2\doc\tutorial\src项目
3. 使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
* 如果采用jdbc独立引用程序配置如下:
<property name="hibernate.current_session_context_class">thread</property>
* 如果采用了JTA事务配置如下
<property name="hibernate.current_session_context_class">jta</property>*/
将以上程序中的:
//获得session session = this.getSession();
修改为:
//获得session session = this.getHibernateTemplate().getSessionFactory().openSession();
这样异常就解决了。