如何修复休眠配置错误和ExceptionInInitializerError

时间:2018-08-31 04:57:57

标签: mysql hibernate

我正在尝试运行一个基本的hellonate hello world程序,该程序将从数据库中获取员工详细信息并打印“ hello employee_name”。但是我不知道哪里出了问题,它不断向我显示无效的配置错误。

Aug 30, 2018 6:19:35 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Aug 30, 2018 6:19:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
Aug 30, 2018 6:19:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 30, 2018 6:19:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 30, 2018 6:19:36 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 30, 2018 6:19:36 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Initial SessionFactory creation failedorg.hibernate.MappingException: invalid configuration
Exception in thread "main" java.lang.ExceptionInInitializerError
    at hibernatePack.hibernateUtil.<clinit>(hibernateUtil.java:28)
    at hibernatePack.model.hibernateHelloWorld.main(hibernateHelloWorld.java:17)
Caused by: org.hibernate.MappingException: invalid configuration
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2158)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
    at hibernatePack.hibernateUtil.<clinit>(hibernateUtil.java:16)
    ... 1 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 26; Element type "hibernate-configuration" must be declared.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at org.dom4j.io.SAXReader.read(SAXReader.java:465)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2155)
    ... 3 more

我在下面发布了我的代码。任何建议将不胜感激。谢谢。

hibernateUtil.java

package hibernatePack;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


public class hibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();

            StandardServiceRegistryBuilder sb = (StandardServiceRegistryBuilder) new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

            StandardServiceRegistry standardServiceRegistry = sb.build();               
            sessionFactory = configuration.buildSessionFactory(standardServiceRegistry);        

        }
        catch (Throwable th) {

        System.err.println("Initial SessionFactory creation failed" + th);

        throw new ExceptionInInitializerError(th);

    }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

hibernateHelloWorld.java类

package hibernatePack.model;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import hibernatePack.hibernateUtil;
import hibernatePack.model.Employee;


public class hibernateHelloWorld {
    public static void main(String[] args) throws Exception {

        SessionFactory sessionFactory = hibernateUtil.getSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        org.hibernate.Transaction tr = session.beginTransaction();

        String strSql ="from Employee o";
        Query query = session.createQuery(strSql);
        List lst = query.list();
        for(Iterator it=lst.iterator();it.hasNext();){

            Employee emp=(Employee)it.next();
            System.out.println("Hello: " + emp.getEmpName());
         }

        tr.commit();
        System.out.println("Data displayed");
        sessionFactory.close();
    }
}

hibernate.cfg.xml文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration>

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springdata</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">pooja31</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="hibernatePack.Employee" />

</session-factory>
</hibernate-configuration>

Employee.java

package hibernatePack.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "emp")
public class Employee implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id; 

    @Column(name="name")
    private String empName;

    @Column(name="salary")
    private int empSalary;    

    @Column(name="designation")
    private String empDesignation;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public int getEmpSalary() {
        return empSalary;
    }

    public void setEmpSalary(int empSalary) {
        this.empSalary = empSalary;
    }

    public String getEmpDesignation() {
        return empDesignation;
    }

    public void setEmpDesignation(String empDesignation) {
        this.empDesignation = empDesignation;
    }




}

2 个答案:

答案 0 :(得分:0)

我认为您的hibernate.cfg.xml存在一些配置问题,因为此hibernate无法创建sessionFactory实例。

使用下面的类并删除hibernate.cfg.xml文件。

    public class HibernateUtil {

   private static StandardServiceRegistry registry;
   private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
      if (sessionFactory == null) {
         try {
            BootstrapServiceRegistry bootstrapRegistry =
                  new BootstrapServiceRegistryBuilder()
                  .applyIntegrator(new EventListenerIntegrator())
                  .build();

            StandardServiceRegistryBuilder registryBuilder = 
                  new StandardServiceRegistryBuilder(bootstrapRegistry);

            Map<String, Object> settings = new HashMap<>();
            settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
            settings.put(Environment.URL, "jdbc:mysql://localhost:3306/springdata?useSSL=false");
            settings.put(Environment.USER, "root");
            settings.put(Environment.PASS, "pooja31");
            settings.put(Environment.HBM2DDL_AUTO, "update");
            settings.put(Environment.SHOW_SQL, true);


            registryBuilder.applySettings(settings);

            registry = registryBuilder.build();

            MetadataSources sources = new MetadataSources(registry)
                  .addAnnotatedClass( Employee.class)


            Metadata metadata = sources.getMetadataBuilder().build();

            sessionFactory = metadata.getSessionFactoryBuilder().build();
         } catch (Exception e) {
            if (registry != null) {
               StandardServiceRegistryBuilder.destroy(registry);
            }
            e.printStackTrace();
         }
      }
      return sessionFactory;
   }

   public static void shutdown() {
      if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
      }
   }
}

答案 1 :(得分:0)

在您的hibernate.cfg.xml中,定义的映射类无效(程序包名称不正确)。更改

<mapping class="hibernatePack.Employee" />

<mapping class="hibernatePack.model.Employee" />

此外,您还需要按照错误中的说明指定“休眠配置”类型。尝试使用以下配置类型。

<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  

尝试解决此问题,它应该可以工作 您可以参考:https://www.javatpoint.com/steps-to-create-first-hibernate-application