Hibernate 4.3.6使用Oracle 11g进行配置

时间:2014-09-10 18:21:48

标签: java oracle hibernate oracle11g

我正在尝试使用Oracle 11g配置Hibernate 4.3.6,但我无法配置...我是     在创建会话时获得空指针异常...我正在进行所有配置     和程序文件,请帮助我找出失败的根本原因

    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.....?

1 个答案:

答案 0 :(得分:2)

如果对未实例化的对象执行操作,则会出现

NullPointerException

因此,您在执行此操作时遇到此异常:

HibernateUtil.getSessionFactory().openSession();

这不过是:

sessionFactory.openSession(); 

根据您在问题中发布的代码,sessionFactory应为null,因为您创建了static变量,如下所示:

private static SessionFactory sessionFactory;

并使用方法HibernateUtil.getSessionFactory()直接访问它,而无需在代码中的任何位置调用createSessionFactory()