hibernate SessionFactory不起作用

时间:2014-12-25 16:16:24

标签: java hibernate java-ee

我有一个hibernate的问题,但我不明白究竟是什么问题 如果你有想法?

private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public List<Customer> listCustomer() {
    return sessionFactory.getCurrentSession().createQuery("FROM customer").list();
}

Main.java

public class Main {

public static void main(String[] args) {

    CustomerDaoImpl dao=new CustomerDaoImpl();

    for(int i=0; i<dao.listCustomer().size(); i++){
        System.out.println(i);
    }   
   }
 }

错误

Exception in thread "main" java.lang.NullPointerException
at com.apps.dao.CustomerDaoImpl.listCustomer(CustomerDaoImpl.java:37)
at com.apps.dao.Main.main(Main.java:8)

1 个答案:

答案 0 :(得分:3)

您必须初始化sessionFactory。在早期的hibernate版本中,你就像这样做了

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

从4.3.0版开始。你必须这样做

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());