Session was already closed

 
Session session = HibernateSessionFactory.getSession();
        try {
            HibernateSessionFactory.beginTransaction();
 
            session.save(user);
 
            HibernateSessionFactory.commitTransaction();
        } catch (HibernateException e) {
            HibernateSessionFactory.rollbackTransaction();
            log.error("", e);
        } finally {
            HibernateSessionFactory.closeSession();
        }

 如上所示的代码段,当运行到HibernateSessionFactory.closeSession();时,程序将报告Session was already closed 错误。

closeSession函数体如下所示

 

        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
 
        if (session != null ) {
            session.close();
        }

 解决方法可以在session.close()之前多加一个判断条件,如下所示

 

        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
 
        if (session != null && session.isOpen()) {
            session.close();
        }

 

至于为什么 我们没有关闭session而session会自动关闭,还有待于了解。我觉得可能是提交Transaction后Hibernate自动关闭了session。

HibernateSessionFactory.commitTransaction()函数体

         public static void commitTransaction(){
                   Transaction tx = (Transaction)txThreadLocal.get();
                   if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
                            tx.commit();
                            txThreadLocal.set(null);
                   }
         }

 


总之,在关闭session前 先来一个如下判断 session != null && session.isOpen()

你可能感兴趣的:(Hibernate)