HibernateUtil中的Session Close错误

被广泛使用的HibernateUtil类

  1. import org.hibernate.*;
  2. import org.hibernate.cfg.*;
  3. public class HibernateUtil {
  4.     private static final SessionFactory sessionFactory;
  5.     static {
  6.         try {
  7.             // 创建SessionFactory
  8.             sessionFactory = new Configuration().configure()
  9.                     .buildSessionFactory();
  10.         } catch (Throwable exception) {
  11.             exception.printStackTrace();
  12.             System.out.println("Initial SessionFactory creation failed.");
  13.             throw new ExceptionInInitializerError(exception);
  14.         }
  15.     }
  16.     // 用两个ThreadLocal类型的属性以保持在一次请求过程中共享单一的Session和Trasaction实例,
  17.     // Session和Trasaction实例可以跨越多个一次请求的多个方法
  18.     public static final ThreadLocal tLoaclsess = new ThreadLocal();
  19.     public static final ThreadLocal tLocaltx = new ThreadLocal();
  20.     // 取得session
  21.     public static Session currentSession() {
  22.         Session session = (Session) tLoaclsess.get();
  23.         // 打开一个新的session,如果当前的不可用
  24.         try {
  25.             if (session == null || !session.isOpen()) {
  26.                 session = openSession();
  27.                 tLoaclsess.set(session);
  28.             }
  29.         } catch (HibernateException exception) {
  30.             exception.printStackTrace();
  31.         }
  32.         return session;
  33.     }
  34.     // 关闭session
  35.     public static void closeSession() {
  36.         Session session = (Session) tLoaclsess.get();
  37.         tLoaclsess.set(null);
  38.         try {
  39.             if (session != null && session.isOpen())
  40.                 session.close();
  41.         } catch (HibernateException exception) {
  42.             exception.printStackTrace();
  43.         }
  44.     }
  45.     // 开始事务
  46.     public static void beginTransaction() {
  47.         Transaction tx = (Transaction) tLocaltx.get();
  48.         try {
  49.             if (tx == null) {
  50.                 tx = currentSession().beginTransaction();
  51.                 tLocaltx.set(tx);
  52.                 System.out.println("beginTransaction");
  53.                 System.out.println(tLocaltx.toString());
  54.             }
  55.         } catch (HibernateException exception) {
  56.             exception.printStackTrace();
  57.         }
  58.     }
  59.     // 关闭事务
  60.     public static void commitTransaction() {
  61.        
  62.         Transaction tx = (Transaction) tLocaltx.get();
  63.         System.out.println(tLocaltx.toString());
  64.         try {
  65.             if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
  66.                 tx.commit();
  67.             }
  68.             tLocaltx.set(null);
  69.             System.out.println("commitTransaction");
  70.         } catch (HibernateException exception) {
  71.             exception.printStackTrace();
  72.         }
  73.     }
  74.     // 回滚事务
  75.     public static void rollbackTransaction() {
  76.         Transaction tx = (Transaction) tLocaltx.get();
  77.         try {
  78.             tLocaltx.set(null);
  79.             if (tx != null && tx.wasCommitted() && !tx.wasRolledBack()) {
  80.                 tx.rollback();
  81.             }
  82.         } catch (HibernateException exception) {
  83.             exception.printStackTrace();
  84.         }
  85.     }
  86.     private static Session openSession() throws HibernateException {
  87.         return getSessionFactory().openSession();
  88.     }
  89.     private static SessionFactory getSessionFactory() throws HibernateException {
  90.         return sessionFactory;
  91.     }
  92. }

使用HibernateUtil进行数据的插入

  1. public class StudentDAOImp implements StudentDAO {
  2.     private static Log log = LogFactory.getLog(StudentDAOImp.class);
  3.     public List getStudent() {
  4.         try {
  5.             Session s = HibernateUtil.currentSession();
  6.             HibernateUtil.beginTransaction();
  7.             List results = s.createQuery("from Student stu").list();
  8.             HibernateUtil.commitTransaction();
  9.             HibernateUtil.closeSession();
  10.             if (results != null && results.size() > 0) {
  11.                 return results;
  12.             }
  13.         } catch (HibernateException e) {
  14.             log.fatal(e);
  15.         }
  16.         return null;
  17.     }
  18.         public boolean saveStudent(Student student) {
  19.         try {
  20.             Session s = HibernateUtil.currentSession();
  21.             HibernateUtil.beginTransaction();
  22.             s.saveOrUpdate(student);
  23.      
  24.             HibernateUtil.commitTransaction();
  25.             HibernateUtil.closeSession();
  26.             return true;
  27.         } catch (HibernateException e) {
  28.             e.printStackTrace();
  29.             log.fatal(e);
  30.         }
  31.         return false;
  32.     }
  33. }

在Struts+Hibernate+Tomcat5.5下运行总是显示

org.hibernate.HibernateException: Session is closed
 at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:94)
 at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:95)
 at com.MyDemo.dao.hibernate.HibernateUtil.commitTransaction(HibernateUtil.java:75)
 at com.MyDemo.dao.hibernate.CloseSessionFilter.doFilter(CloseSessionFilter.java:25)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
 at com.MyDemo.util.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:26)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:875)
 at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
 at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
 at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
 at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
 at java.lang.Thread.run(Thread.java:619)

 

检查后发现HibernateUtil.commitTransaction时Session已经关闭.数据也插入不了,网上找不到解决方法.

后来看到使用在public boolean saveStudent(Student student)中加入

HibernateUtil.beginTransaction();
s.saveOrUpdate(student);
s.flush();
HibernateUtil.commitTransaction();

数据是可以插入了,但报错依旧.

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

arthurhgd

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值