在部署Maven Web Application JSF-2.2 +Hibernate时,我得到一个nullPointerException
ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host]
.[/maven-project].[FacesServlet]] (http-localhost/127.0.0.1:8080-1)
JBWEB000236: Servlet.service() for servlet FacesServlet threw exception:
java.lang.NullPointerException
at com.ubosque.mb.CiudadanoMB.getAllCiudadanos(CiudadanoMB.java:28)
[classes:]当我查看com.ubosque.mb.CiudadanoMB.getAllCiudadanos(CiudadanoMB.java:28)时,会出现下面这行:
sesion = HibernateSessionFactory.getSessionFactory().getCurrentSession();HibernateSessionFactory类:
private static SessionFactory sessionFactory = setSessionFactory();
private static SessionFactory setSessionFactory() {
try {
if (sessionFactory == null) { // if session == null
Configuration config = new Configuration().configure();
StandardServiceRegistryBuilder regbuild = new StandardServiceRegistryBuilder();
StandardServiceRegistry builder = regbuild.applySettings(config.getProperties()).build();
sessionFactory = config.buildSessionFactory(builder);
}// if session == null
} catch (Exception e) {
e.printStackTrace();
}// try - catch
return sessionFactory;
}// setSessionFactory
public static SessionFactory getSessionFactory() {
return sessionFactory;
}似乎找不到我的问题所在,我只是在学习Hibernate。提前谢谢。
发布于 2015-05-14 03:49:09
private static SessionFactory sessionFactory = setSessionFactory();由于某些原因,这行代码失败,并将sessionFactory保留为null。显然,这会在抛出NPE之前发生,这会导致HibernateSessionFactory.getSessionFactory()返回null,这反过来又会导致NPE,所以我建议您检查一下输出,并检查setSessionFactory打印到标准输出的堆栈。
而且,这种实例化会话工厂的方式很糟糕--您无法确定它是否被实例化了。这个异常可能不应该被捕获,但应该抛出一个IllegalStateException (最有可能的),并将最初的异常作为原因:
try {
// ...
} catch (Exception e) {
throw new IllegalStateException(e);
}// try - catch这样,如果您的应用程序崩溃,您实际上有一种方法,至少知道它。
发布于 2015-05-14 06:12:38
当您调用方法getCurrentSession()时,hibernate意味着会话的实例已经创建。但这不是真的(它是null,因此抛出NullPointerEx)。首先,您必须使用openSession()方法创建会话,然后您可以调用getCurrentSession()方法。
https://stackoverflow.com/questions/30223718
复制相似问题