我已经创建了一个使用Hibernate的类的简单示例,但是我收到以下错误:
Initial SessionFactory creation failed. java.lang.ExceptionInInitializerError
java.lang.ExceptionInInitializerError
at org.hibernate.cfg.Configuration.reset(Configuration.java:249)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:216)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:220)
at it.univaq.mwt.tplabs0.Test.main(Test.java:14)
Caused by: java.lang.NullPointerException
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:167)
at org.hibernate.cfg.Environment.<clinit>(Environment.java:585)
... 4 more
Exception in thread "main" java.lang.NullPointerException
at it.univaq.mwt.tplabs0.Test.main(Test.java:20)
我的测试课程:
package it.univaq.mwt.tplabs0;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
SessionFactory sessionFactory = null;
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed. " + ex);
ex.printStackTrace();
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
System.out.println("Creating element");
Element el = new Element("prova", 1);
session.save(el);
System.out.println("Committing Tx");
session.getTransaction().commit();
System.out.println("Closing Session");
if (session.isOpen())
session.close();
}
}
我的Hibernate配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">master</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="hibernate.connection.username">master</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<mapping class="it.univaq.mwt.tplabs0.Element" resource="it/univaq/mwt/tplabs0/Element.hbm.xml"/>
</session-factory>
</hibernate-configuration>
我的图书馆:
启动这个简单的执行我从上面得到了错误。我正在使用的数据库是Oracle 11g。
发生了什么事?
答案 0 :(得分:1)
您的代码所说的内容:
1. SessionFactory sessionFactory = null;
2. try {
3. sessionFactory = new Configuration().configure().buildSessionFactory();
4. } catch (Throwable ex) {
5. System.err.println("Initial SessionFactory creation failed. " + ex);
6. ex.printStackTrace();
7. }
8.
9. Session session = sessionFactory.getCurrentSession();
// Here you are trying to access the Session which is not even created
您正在尝试访问未在CurrentSessionContext中配置或根本未创建的会话。
将第9行的代码替换为:
Session session = sessionFactory.openSession();
你会看到自己。