我在部署 Maven Web 应用程序 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
。提前致谢。
最佳答案
private static SessionFactory sessionFactory = setSessionFactory();
由于某种原因,该行失败,并使 sessionFactory 保持为空。显然,这种情况发生在抛出 NPE 之前,这会导致 HibernateSessionFactory.getSessionFactory()
返回 null,进而导致 NPE,因此我建议检查您的输出并检查 setSessionFactory
打印到标准输出的堆栈跟踪。
此外,这种实例化 session 工厂的方式很脏 - 您无法确定它是否确实被实例化。该异常可能不应该在那里被捕获,但应该抛出一个 IllegalStateException (最有可能),并以原始异常为原因:
try {
// ...
} catch (Exception e) {
throw new IllegalStateException(e);
}// try - catch
这样,如果您的应用程序崩溃,您实际上至少有办法知道它。
关于java - 创建Session时getCurrentSession返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30223718/