欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

测试SessionFactory失败!

程序员文章站 2022-07-05 09:57:52
...
package springWebwork2;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
import org.apache.commons.logging.*;
import java.util.*;

import manager.*;

public class HibernateUtil {

private static Log log = LogFactory.getLog(HibernateUtil.class);

private static final SessionFactory sessionFactory;

static {
  try {
   // Create the SessionFactory
   sessionFactory = new Configuration().configure().buildSessionFactory();
  } catch (Throwable ex) {
   log.error("创建SessionFactory失败:", ex);
   throw new ExceptionInInitializerError(ex);
  }
}

//使用ThreadLocal实现线程安全
public static final ThreadLocal LocalSession = new ThreadLocal();

public static Session currentSession() throws HibernateException {
  Session s = (Session) LocalSession.get();
  // Open a new Session, if this Thread has none yet
  if (s == null) {
   s = sessionFactory.openSession();
   LocalSession.set(s);
  }
  return s;
}

public static void closeSession() throws HibernateException {
  Session s = (Session) LocalSession.get();
  LocalSession.set(null);
  if (s != null)
   s.close();
}
//测试代码
public static void main(String[] args) throws Exception {
  Session session = HibernateUtil.currentSession();
  Transaction tx = session.beginTransaction();
  //创建数据对象并插入表
  Manager B = new Manager();
  //B.setBlockname("新区");
  //B.setShoworder(0);
  //相当于insert
  //session.save(B);

  //用list方法查询数据
  Query q = session.createQuery("from manager"); //用对象类名,而非表名
  List l = q.list();//返回一个List接口,用来遍历结果集

  for (int i = 0; i < l.size(); i++) {
   B = (Manager) l.get(i);
   System.out.println(B.toString());
  }
  //更新数据
  //Query qq = session.createQuery("from SimpleUser");
  //B = (Block) session.load(Block.class, new Integer(1));
  //B.setBlockname("其它");
  //tx.commit();
  //关闭
  HibernateUtil.closeSession();
}
}

执行到
sessionFactory = new Configuration().configure().buildSessionFactory();
时出现异常!我用的是eclipse M1.7 + hibernate2 + postgreSql
我刚刚学习Hibernate ,请给点帮助谢谢!