线程“main”java.lang.ExceptionInInitializerError中的Hibernate异常

时间:2016-01-20 21:16:43

标签: java hibernate nullpointerexception

我是Hibernate的新手,所以请放轻松我吧! 我只是尝试打开和关闭一个hibernate会话,如下所示: Program.java如下:     package com.simpleprogrammer;

import org.hibernate.Session;

public class Program {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        Session session = HibernateUtilities.getSessionFactory().openSession();
        session.close();
    }
}

和我的HibernateUtilities.java文件如下:

package com.simpleprogrammer;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtilities {
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static {
        try
        {
            Configuration configuration = new Configuration().configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (HibernateException exception)
        {
            System.out.println("Problem creating session factory");
        }
    }
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }
}

最后我的hibernate.cfg.xml文件如下:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.password">password</property>
    <property name="connection.url">jdbc:mysql://localhost:3306</property>
    <property name="connection.username">appuser</property>
    <property name="connection.default_schema">protien_tracker</property>
    <property name="connection.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.show_sql">true</property>

      <!-- <property name="hbm2ddl.auto">update</property> -->
  </session-factory>
</hibernate-configuration>

当我尝试运行它时,我得到一个空指针异常,堆栈跟踪如下:

"C:\Program Files\Java\jdk1.8.0_45\bin\java" -Didea.launcher.port=7537 "-Didea.launcher.bin.path=C:\Users\John Stafford\AppData\Roaming\JetBrains\IntelliJ IDEA 15.0.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_45\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\rt.jar;C:\Java\intellij\ProtienTracker\out\production\ProtienTracker;C:\Java\intellij\ProtienTracker\lib\hibernate-jpa-2.0-api-1.0.1.Final.jar;C:\Java\intellij\ProtienTracker\lib\antlr-2.7.7.jar;C:\Java\intellij\ProtienTracker\lib\hibernate-commons-annotations-4.0.2.Final.jar;C:\Java\intellij\ProtienTracker\lib\jboss-logging-3.1.0.GA.jar;C:\Java\intellij\ProtienTracker\lib\dom4j-1.6.1.jar;C:\Java\intellij\ProtienTracker\lib\jboss-transaction-api_1.1_spec-1.0.1.Final.jar;C:\Java\intellij\ProtienTracker\lib\javassist-3.15.0-GA.jar;C:\Java\intellij\ProtienTracker\lib\hibernate-core-4.2.2.Final.jar;C:\Java\intellij\ProtienTracker\lib\mysql-connector-java-5.0.4-bin.jar;C:\Users\John Stafford\AppData\Roaming\JetBrains\IntelliJ IDEA 15.0.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.simpleprogrammer.Program
Hello world!
Jan 20, 2016 9:03:37 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Jan 20, 2016 9:03:37 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.2.Final}
Jan 20, 2016 9:03:37 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 20, 2016 9:03:37 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 20, 2016 9:03:37 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jan 20, 2016 9:03:37 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jan 20, 2016 9:03:38 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jan 20, 2016 9:03:38 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jan 20, 2016 9:03:38 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Jan 20, 2016 9:03:38 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Jan 20, 2016 9:03:38 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306]
Jan 20, 2016 9:03:38 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=appuser, password=****, dialect=org.hibernate.dialect.MySQLDialect, show_sql=true, default_schema=protien_tracker}
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.simpleprogrammer.Program.main(Program.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.lang.NullPointerException
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
    at com.simpleprogrammer.HibernateUtilities.<clinit>(HibernateUtilities.java:18)
    ... 6 more

Process finished with exit code 1

有人知道我在这里做错了什么吗?

2 个答案:

答案 0 :(得分:1)

以下是创建会话的示例:HibernateUtil

public class HibernateUtil {

private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory() {

    if(sessionFactory==null)
    {

        try{
             sessionFactory = new AnnotationConfiguration().
                       configure().
                       //addPackage("com.xyz") //add package if used.
                       addAnnotatedClass(User.class).
                       buildSessionFactory();
          }catch (Throwable ex) { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
          }
    }
    return sessionFactory;

}

}

使用会话

public class Dao {


public void save(Object obj) {


    SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    Session session=sessionFactory.openSession();
    try{

        session.beginTransaction();
        session.save(obj);
        session.getTransaction().commit();
        session.close();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}

确保你在lib中有jdbc jar

答案 1 :(得分:1)

如果您使用的是Hibernate 4.3 ++,请更改HibernateUtilities类中的以下行。

configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");

StandardServiceRegistryBuilder serviceBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(serviceBuilder.build());

hibernate.cfg.xml

进行以下更改
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/protien_tracker</property>
<property name="connection.username">appuser</property>
<property name="connection.password">password</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>