【问题标题】:Hibernate Could not read mappings from resource: Employee.hbm.xmlHibernate 无法从资源读取映射:Employee.hbm.xml
【发布时间】:2015-09-12 05:32:07
【问题描述】:

从以下链接执行简单的休眠程序时出现以下错误 http://www.tutorialspoint.com/hibernate/hibernate_examples.htm

创建 sessionFactory object.org.hibernate.MappingException 失败: 无法从资源中读取映射:Employee.hbm.xml 中的异常 线程“主”java.lang.ExceptionInInitializerError 在 ManageEmployee.main(ManageEmployee.java:21) 原因: org.hibernate.MappingException:无法从资源中读取映射: Employee.hbm.xml 在 org.hibernate.cfg.Configuration.addResource(Configuration.java:484) 在 org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1453) 在 org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1421) 在 org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1402) 在 org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1378) 在 org.hibernate.cfg.Configuration.configure(Configuration.java:1298) 在 org.hibernate.cfg.Configuration.configure(Configuration.java:1284) 在 ManageEmployee.main(ManageEmployee.java:18) 引起: org.hibernate.MappingException:无法解析映射文档 输入流在 org.hibernate.cfg.Configuration.addInputStream(Configuration.java:430) 在 org.hibernate.cfg.Configuration.addResource(Configuration.java:481) ... 7 更多原因:org.dom4j.DocumentException:www.hibernate.org 嵌套异常:www.hibernate.org at org.dom4j.io.SAXReader.read(SAXReader.java:484) 在 org.hibernate.cfg.Configuration.addInputStream(Configuration.java:421) ... 8 更多

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 文件放在哪里?
  • 你可以从这个链接下载我的项目myslams.com/test/hibernate.zip

标签: java hibernate


【解决方案1】:

检查项目中正确包中的 Employee.hbm.xml,并在下面的 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>

【讨论】:

    【解决方案2】:

    显然已找到 Employee.hbm.xml,但 Hiberante 无法读取该文件。尝试使用此代码替换您的文件,替换 YOUR PATH HERE (com.something.something) 为您的真实路径。

    <?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>
    

    【讨论】:

    • 我只使用默认包。所以他们不是 com.something.something 。所以我试过没有包标签和 package="" 但仍然给出相同的错误
    【解决方案3】:

    在您的 Employee.hbm.xml 中编辑 class name="your.packageName.Employee"

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多