错误:&#34;无法创建sessionFactory object.org.hibernate.boot.registry.classloading.spi.ClassLoadingException:无法加载类<pojo>&#34;

时间:2017-05-07 09:03:36

标签: java hibernate jdbc

我看到&#34;类似&#34;许多网站的问题,但无法解决我的问题。我正在使用以下软件/配置。

1.Eclipse版本:Neon.3发布(4.6.3)

2.Hibernate Tools 5.1.3.v20170210-1113

3.MySql 5.6.36

当我运行持久性&#34; ManageEmployee&#34;时,我收到以下错误类。

May 07, 2017 1:53:26 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
May 07, 2017 1:53:26 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.max_fetch_depth=5, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=10000, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.password=****, hibernate.connection.pool_size=5}
May 07, 2017 1:53:27 PM org.hibernate.spatial.integration.SpatialService <init>
INFO: HHH80000001: hibernate-spatial integration enabled : true
May 07, 2017 1:53:27 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 07, 2017 1:53:29 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
May 07, 2017 1:53:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/testdb]
May 07, 2017 1:53:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
May 07, 2017 1:53:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
May 07, 2017 1:53:30 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 5 (min=1)
May 07, 2017 1:53:30 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 07, 2017 1:53:31 PM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
Failed to create sessionFactory object.org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Employee]
Exception in thread "main" java.lang.ExceptionInInitializerError
    at hibernatePackage.ManageEmployee.main(ManageEmployee.java:20)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Employee]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:348)
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:104)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:147)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:141)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at hibernatePackage.ManageEmployee.main(ManageEmployee.java:17)
Caused by: java.lang.ClassNotFoundException: Could not load requested class : Employee
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:336)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:345)
    ... 9 more

Package explorer hierarchy snapshot

Hibernate映射文件:Employee.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

    <hibernate-mapping>
       <class name="hibernatePackage.Employee" table="EMPLOYEE">
          <meta attribute="class-description">
             This class contains the employee detail. 
          </meta>
          <id name="id" type="int" column="id">
             <generator class="native"/>
          </id>
          <property name="firstName" column="first_name" type="string"/>
          <property name="lastName" column="last_name" type="string"/>
          <property name="salary" column="salary" type="int"/>
       </class>
    </hibernate-mapping>

Hibernate配置文件:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory name="">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <mapping class="Employee" package="hibernatePackage" resource="resource"/>

  <mapping resource="hibernatePackage/Employee.hbm.xml"/>
  <mapping class="hibernatePackage.Employee"/>
 </session-factory>
</hibernate-configuration>

POJO类:Employee.java

package hibernatePackage;

public class Employee {
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;  

   public Employee() {}
   public Employee(String fname, String lname, int salary) {
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

要持久化对象的类:ManageEmployee.java

package hibernatePackage;

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

import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                    (Employee)session.get(Employee.class, EmployeeID); 
         employee.setSalary( salary );
         session.update(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee = 
                   (Employee)session.get(Employee.class, EmployeeID); 
         session.delete(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}

2 个答案:

答案 0 :(得分:1)

源代码怎么样?

我已经发布了你的stackTrace片段:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hb_employee_tracker?useSSL=false</property>

        <property name="hibernate.connection.username">hbemployee</property>
        <property name="hibernate.connection.password">hbemployee</property>

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.pool_size">1</property> 
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property> 
        <property name="current_session_context_class">thread</property>

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

也许它出了什么问题?

- UPD --- 我改变了一些东西,并没有触及其他方法,比如添加,列出ets。 另外我不知道如何制作好的xml映射,所以如果你也不知道,请使用像我这样的java注释。

所以,我的下面的事情:

<强> hibernate.cfg.xml中

    package hibernatepackage.entity;

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

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

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

    public Employee() {
    }

    public Employee(String fname, String lname, int salary) {
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String first_name) {
        this.firstName = first_name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String last_name) {
        this.lastName = last_name;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
}

<强> Employee.java

package hibernatepackage.persistance;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import hibernatepackage.entity.Employee;

public class ManageEmployee {

   private static SessionFactory factory; 

   public static void main(String[] args) {

       factory = new Configuration()
               .configure("hibernate.cfg.xml")
               .addAnnotatedClass(Employee.class)
               .buildSessionFactory();

       Session session = factory.getCurrentSession();

       Employee emp0 = new Employee("John", "Doe", 1000);
       Employee emp1 = new Employee("Richard", "Roe", 2000);
       Employee emp2 = new Employee("Joe", "Bloggs", 3000);
       Employee emp3= new Employee("Another", "Everyman", 4000);

       try {

           session.beginTransaction();

           session.save(emp0);
           session.save(emp1);
           session.save(emp2);
           session.save(emp3);

           session.getTransaction().commit();

    } finally  {

        factory.close();
    }



   }
}

这是你的persistense课没有和另一个东西: ManageEmployee.java

/myfeed.php?start=2013-12-01&end=2014-01-12&_=1386054751381

上面的代码为数据库添加了4个新实体。我在MySQL localhost DB上测试它。

答案 1 :(得分:0)

为什么要在hibernate配置文件中映射<?php $title = 'My awesome title'; /** Here your php code to get the content and assign variable to all nodes **/ $title_old = $title; /** Get the info your xml script or cached XML data **/ $title_new = 'My awesome title'; /** Use YOUR new value! - requestt the content again after someone clicked the save button or use a crontab to get info on changes every x minutes, hours or days **/ if($title_new == $title_old){ $title_changed = 'No changes detected to the title node'; echo $title_changed . ': The title is &quot;' . $title . '&quot;'; }else{ $title_changed = 'The title node has been changed'; echo $title_changed . ': The new title is &quot;' . $title . '&quot;'; } ?> 文件和hbm类?

<强>问题:

您只需要在Pojo中映射Employee.hbm文件,Hibernate.cfg.xml类已经映射到Employee.java文件中,这是导致此问题的原因异常。

如果您将其映射到Employee.hbm,则hibernate会查找此类中的Hibernate.cfg.xml配置,从而触发Annotations

<强>解决方案:

因此,您的Hibernate配置文件将只映射ClassLoadingException文件:

Employee.hbm

Hibernate Docs:

您可以查看Hibernate Configuration File ExampleUsing Native Hibernate APIs and hbm.xml Mappings tutorial了解详情。