简体   繁体   中英

Hibernate Could not read mappings from resource: Employee.hbm.xml

I am getting the following error while executing a simple hibernate program from the below link http://www.tutorialspoint.com/hibernate/hibernate_examples.htm

Failed to create sessionFactory object.org.hibernate.MappingException: Could not read mappings from resource: Employee.hbm.xml Exception in thread "main" java.lang.ExceptionInInitializerError at ManageEmployee.main(ManageEmployee.java:21) Caused by: org.hibernate.MappingException: Could not read mappings from resource: Employee.hbm.xml at org.hibernate.cfg.Configuration.addResource(Configuration.java:484) at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1453) at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1421) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1402) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1378) at org.hibernate.cfg.Configuration.configure(Configuration.java:1298) at org.hibernate.cfg.Configuration.configure(Configuration.java:1284) at ManageEmployee.main(ManageEmployee.java:18) Caused by: org.hibernate.MappingException: Could not parse mapping document in input stream at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:430) at org.hibernate.cfg.Configuration.addResource(Configuration.java:481) ... 7 more Caused by: org.dom4j.DocumentException: www.hibernate.org Nested exception: www.hibernate.org at org.dom4j.io.SAXReader.read(SAXReader.java:484) at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:421) ... 8 more

Employee.java

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

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(); 
  }
  }
  }

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="Employee" table="EMPLOYEE">
  <meta attribute="class-description">
     This class contains the employee detail. 
  </meta>
  <id name="id" type="int" column="id">
     <generator class="sequence"/>
  </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.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate           Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-   configuration-3.0.dtd">

<hibernate-configuration>
<session-factory name="sessionFactory">

<!-- Database connection settings -->

<property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
<property name="connection.url">jdbc:db2://172.18.75.21:60008/tinuat</property>

<!-- <property name="connection.driver_class">net.sf.log4jdbc.DriverSpy</property>
<property name="connection.url">jdbc:log4jdbc:postgresql://172.19.65.152:5432/NIR</property>-->

<property name="connection.username">samol</property>
<property name="connection.password">samolteam</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">30</property> 
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.DB2Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.connection.release_mode">auto</property>


<!-- Echo all executed SQL to stdout -->

<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">false</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

检查您项目中正确包中的 Employee.hbm.xml,并使用正确的包名在 bellow xml 中设置类名。

<hibernate-mapping> <class name="yourpackageName.Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="sequence"/> </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>

Apparently the Employee.hbm.xml is found but Hiberante can not read the file. Try to replace your file with this code replacing the YOUR PATH HERE (com.something.something) for your real path.

<?xml version="1.0" ?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  <hibernate-mapping package="YOUR PATH HERE (com.something.something)">
    <class name="Employee" table="EMPLOYEE" lazy="false">
        <id name="id" column="id" type="long">
            <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="long"/>
    </class>        
  </hibernate-mapping>

Edit class name="your.packageName.Employee" in your Employee.hbm.xml :

<hibernate-mapping>
<class name="your.packageName.Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="sequence"/>
      </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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM