2015-05-13 94 views
0

我得到一個nullPointerException進行部署時,當返回null我Maven Web Application JSF-2.2 +Hibernate的getCurrentSession創建會話

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。提前Thanx。

回答

0
private static SessionFactory sessionFactory = setSessionFactory(); 

此行由於某種原因失敗,並將sessionFactory保留爲null。這種情況發生在你的NPE被拋出之前,顯然,這導致HibernateSessionFactory.getSessionFactory()返回null,這反過來導致你的NPE,所以我建議你通過你的輸出並檢查setSessionFactory打印到你的標準輸出的棧跟蹤。

此外,這種實例化會話工廠的方式很髒 - 您無法確定它是否實際實例化。該異常可能不應該在那裏抓住了,但應與原來的異常作爲原因拋出IllegalStateException(最有可能):

try { 
    // ...       
} catch (Exception e) { 
    throw new IllegalStateException(e); 
}// try - catch 

這樣,如果你的應用程序崩潰,你實際上有至少寂寂的方式它。

0

當您調用方法getCurrentSession()時,hibernate意味着已創建會話的實例。但它不是真的(它是空的,因此它拋出NullPointerEx)。首先,您必須創建會話方法openSession(),然後您可以調用方法getCurrentSession()