2014-09-10 78 views
-2

我想用Oracle 11g配置Hibernate 4.3.6,但我無法配置...我是
在創建會話時得到空指針異常... i我把所有的配置 和程序文件,請幫我弄失敗的根本原因休眠4.3.6使用Oracle 11g配置

hibernate.cfg.xml 

    <hibernate-configuration> 
    <session-factory> 

    <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
    <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:XE</property> 
    <property name="username">TEST</property> 
    <property name="password">ORACLE</property> 
    <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property> 
    <property name="show_sql">true</property> 
    <property name="hibernate.connection.pool_size">5</property> 
    </session-factory> 
</hibernate-configuration> 

HibernateUtil.java 

public class HibernateUtil { 
    private static SessionFactory sessionFactory; 
    private static ServiceRegistry serviceRegistry; 
    public static SessionFactory createSessionFactory() { 
     try{ 
      Configuration configuration = new Configuration(); 
      configuration.configure("hibernate.cfg.xml"); 
      serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
        configuration.getProperties()).build(); 
      sessionFactory = configuration.buildSessionFactory(serviceRegistry); 
      return sessionFactory; 
     } 
     catch (Throwable ex) { 
      // Make sure you log the exception, as it might be swallowed 
      System.err.println("Initial SessionFactory creation failed." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 
    public static SessionFactory getSessionFactory() { 
      return sessionFactory; 
    } 
} 

FetchTest.java 

public class FetchTest { 
<br> 
    public static void main(String a[]){<br> 
     System.out.println("*********************** Inside Main ***********************"); 

     <br><br> 
      Session session = HibernateUtil.getSessionFactory().openSession(); 
    } 
} 

Output : - 

*********************** Inside Main *********************** 
Exception in thread "main" java.lang.NullPointerException 
    at com.naveen.org.FetchTest.main(FetchTest.java:18) 

Please give your suggestions how to get ride from this.....? 

回答

2

NullPointerException來,如果你沒有被實例化的對象上執行的操作。

所以,你同時做得到此異常:

HibernateUtil.getSessionFactory().openSession(); 

這無非是:

sessionFactory.openSession(); 

按照你在你的問題張貼代碼sessionFactory應該是null因爲你創造了一個static變量是這樣的:

private static SessionFactory sessionFactory; 

並使用方法HibernateUtil.getSessionFactory()直接訪問它,而無需在代碼中的任何位置調用createSessionFactory()

PS:您需要在SO中直接發佈基本問題之前進行一些基本分析。