public void updateAccount(Account account) {
Session session = AccountUtil.getSession();
try{
session.beginTransaction();
Account newAccount = (Account)session.load(Account.class,new Long (account.getOid()));
newAccount.setBal(account.getBal());
session.flush();
session.getTransaction().commit();
}catch(Exception ee){
ee.printStackTrace();
}finally{
session.close();
AccountUtil.closeSessionFactory();
}
}
public Account selectAccount(Account account) {
Session session = AccountUtil.getSession();
String hql = "from Account a where a.oid=?";
Account newAccount = null;
try{
session.beginTransaction();
newAccount = (Account)session.createQuery(hql).setLong(0, new Long(account.getOid())).uniqueResult();
session.getTransaction().commit();
}catch(Exception ee){
ee.printStackTrace();
}finally{
session.close();
AccountUtil.closeSessionFactory();
}
return newAccount;
}小弟在写模拟ATM机器,刚刚hibernate入门~
如果
selectAccount(); //查询余额方法
之后紧接着运行
updateAccount(); 
方法就出现空指针异常!
在updateAccount(); 里的session.beginTransaction();出错。
我打印了看了下,SESSION 为空。估计是SESSION还没得到连接,就执行了updateAccount()方法了!
如果selectAccount();方法里AccountUtil.closeSessionFactory(); 这段关于SESSION工厂注释就没问题了!
但是我不想注释掉,有没有其他解决办法呢?

解决方案 »

  1.   

    Lz 麻烦你把AccountUtil 这个类贴出来  在把错误也贴出来
      

  2.   


    AccountUtil这里面的代码肯定有错
    AccountUtil.closeSessionFactory();//我估计是这个错误,这个得在确定程序结束后才能删。否则update的时候你就不能获得session了
      

  3.   

    你的AccountUtil类中,如果sf是通过静态语句块获得的
    当你执行了一次AccountUtil.closeSessionFactory();
    之后,SessionFactory就为空了,
    没有了SessionFactory,
    Session自然也得不到AccountUtil.closeSessionFactory()这个方法的确定不用到Session的时候才能关
      

  4.   

    给你一段代码参考下,要理解其中package com.tarena.whl.ebank.biz.util;import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;public class HibernateUtil {
    public static SessionFactory sf=null;

    static{
    sf=new Configuration().configure().buildSessionFactory();
    }

    public static SessionFactory getSessionFactory(){
    return sf;
    }

    public static Session getSession(){
    Session s=null;
    if(!sf.isClosed()){
    s=sf.openSession();
    }
    return s;
    }

    public static void closeSessionFactory(){
    if(sf.isClosed()){
    sf.close();
    }
    }
    }
      

  5.   

    去掉selectAccount方法里的 AccountUtil.closeSessionFactory();这个方法~
      

  6.   

     AccountUtil.closeSessionFactory();干什么用的?画蛇添足嫌疑,建议彻底去掉!
      

  7.   

    fzdxwhl2007 <-- 谢谢!
    你是达内的?你给的代码,跟达内老师代码一摸一样~
      

  8.   

    说明你调用的是两个不同的SESSION,在你释放第一个SESSION前是不可能再次生成另外的SESSION,因为你用的是开发工具自动生成的HIBERNATE SESSION生成方式代码.你给SESSION加个锁,让进行查询的那个SESSION具有独占性,在释放这个SESSION前执行SELECTACCOUNT操作,应该就不会报错了.试试看......
      

  9.   

    chong023  <--
    谢谢你啊,我已经搞明白了。