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工厂注释就没问题了!
但是我不想注释掉,有没有其他解决办法呢?
解决方案 »
- 请问下列两个错误怎么解决,本人刚学Java
- 求助:Java Nio 保持长连接分发消息
- 求牛人指点一下 坐等哦!
- 指点一下,运行结果提示:Exception in thread "main" java.lang.NoSuchMethodError: main
- 这个需求怎么写啊?脑力不够。。。。。。。。。。。。。。。。55
- tomcat连接池配置问题
- java中如何实现批量上传图片,用什么组件?
- 我的右键菜单actionperformed怎么不出效果(急)
- 向ORACLE 的blob类型的表INSERT ,失败 ORA-00600 错误? 怎么办?
- 急问:利用什么方法可将两个CheckBox值与某一信息绑在一起??
- java文件操作问题
- 怎么设置List的显示宽度
AccountUtil这里面的代码肯定有错
AccountUtil.closeSessionFactory();//我估计是这个错误,这个得在确定程序结束后才能删。否则update的时候你就不能获得session了
当你执行了一次AccountUtil.closeSessionFactory();
之后,SessionFactory就为空了,
没有了SessionFactory,
Session自然也得不到AccountUtil.closeSessionFactory()这个方法的确定不用到Session的时候才能关
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();
}
}
}
你是达内的?你给的代码,跟达内老师代码一摸一样~
谢谢你啊,我已经搞明白了。