我用hibernate做了一个登陆验证,第一次登陆后不管成功或者失败,再次打开登陆页面,提交数据后就会返回:session is closed,代码如下:
public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();        if (session == null) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }        return session;
上面是生成session的函数,
public boolean loginConfirm(String username,String password )
{
String name ,pass;
Session session = HibernateSessionFactory.currentSession();
Transaction tx = null;
boolean flag = false;
try{
tx = session.beginTransaction();
Test test = new Test(username,password);
Query user=session.createQuery("from Test as c where c.username=:name and c.password=:pass");
user.setString( "name",username);
user.setString( "pass",password);
java.util.List result = user.list();
tx.commit();
if(result.isEmpty())
flag = false;
else
flag = true;
}catch(HibernateException e)
{
if(tx!= null){
 tx.rollback();
}
throw e;
}finally{
session.close();
}
return flag; }
我用过一次session后,我关闭它,我再次登陆的时候,应该再调用currentSession() 生成session,但是在我单步执行的时候,到了 tx = session.beginTransaction();就会跳到异常处理那,

解决方案 »

  1.   

    你的配置文件中hibernate-config.xml文件中,sessionFacotry是怎么定义的呢?是不是设置了single的呢?
      

  2.   

    是不是要考虑你得server怎么处理请求?如果是多进程的话,是不是你的session就不能关闭了?真的是在乱说话,我是乱猜得。
      

  3.   

    你的配置文件中hibernate-config.xml文件中,sessionFacotry是怎么定义的呢?是不是设置了single的呢?
    ------------------------------------------------------------------------------------
    是MyEclipse自动生成的配置文件,我找了,里面没有你说的内容
      

  4.   

    你把你那句session.close();换成SessionFactory.closesession();试试看
      

  5.   

    是你Session生成的那个方法写的不对,第一次登陆时没有Session,进入if,能够创建并打开Session,之后返回,然后你关闭了,下次再进来找Session时,能找到Session,不是null,但是这个Session已经关闭,无法进入if语句,也就无法open,直接返回关闭状态的Session,所以不行,其实如果你是单独使用Hibernate的话没有必要单独写一个方法来生成Session(而且还是static方法。。),每次执行之前生成然后马上关闭就好了,如果非要代码重用的话需要改一下你生成Session的逻辑,而且强烈建议不要使用static方法