无法创建sessionFactory object.org.hibernate.HibernateException [英] Failed to create sessionFactory object.org.hibernate.HibernateException

查看:71
本文介绍了无法创建sessionFactory object.org.hibernate.HibernateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我是新来的hibernate framework.when我正在运行hibernate示例代码它工作正常,如果互联网连接可用。如果互联网连接不可用,那么它不工作,并给出如下错误: p>

  log4j:WARN记录器(org.hibernate.cfg.Environment)中找不到appender。 
log4j:WARN请正确初始化log4j系统。
无法创建sessionFactory object.org.hibernate.HibernateException:无法解析配置:/hibernate.cfg.xml
线程main中的异常java.lang.ExceptionInInitializerError $ b $ com.hb中的异常.example.ManageEmployee.main(ManageEmployee.java:20)
导致:org.hibernate.HibernateException:无法解析配置:/hibernate.cfg.xml $ b $在org.hibernate.cfg.Configuration。在org.hibernate.cfg.Configuration.configure(Configuration.java:1425)上执行配置(Configuration.java:1491)
(org.hibernate.cfg.Configuration.configure(Configuration.java:1425)

at com.hb.example.ManageEmployee.main(ManageEmployee.java:17)
引起:org.dom4j.DocumentException:www.hibernate.org嵌套异常:www.hibernate.org
在org.dom4j.io.SAXReader.read(SAXReader.java:484)
在org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 3 more

我的示例代码是lik e下面:
Employee.java:

  package com.hb.example; 

public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
$ b $ public Employee(){}
public Employee(String fname,String lname,int salary){
this.firstName = fname;
this.lastName = lname;
this.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;


$ / code>

ManageEmployee.java:

  package com.hb.example; 

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;
导入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);
抛出新的ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
$ b $ * / *在数据库中添加少量员工记录* /
Integer empID1 = ME.addEmployee(Zara,Ali,1000);
Integer empID2 = ME.addEmployee(Daisy,Das,5000);
Integer empID3 = ME.addEmployee(John,Paul,10000);

/ *列出所有员工* /
ME.listEmployees();

/ *更新员工记录* /
ME.updateEmployee(empID1,5000);

/ *从数据库中删除雇员* /
ME.deleteEmployee(empID2);

/ *列出新员工名单* /
ME.listEmployees();
}
/ *在数据库中创建雇员的方法* /
public Integer addEmployee(String fname,String lname,int salary){
Session session = factory.openSession );
Transaction tx = null;
Integer employeeID = null;
尝试{
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();
}
返回employeeID;

读取所有员工的方法* /
public void listEmployees(){
Session session = factory.openSession();
Transaction tx = null;
尝试{
tx = session.beginTransaction();
列出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();

$ b $ *更新员工工资的方法* /
public void updateEmployee(Integer EmployeeID,int salary){
Session session = factory.openSession ();
Transaction tx = null;
尝试{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class,EmployeeID);
employee.setSalary(工资);
session.update(employee);
tx.commit();
} catch(HibernateException e){
if(tx!= null)tx.rollback();
e.printStackTrace();
} finally {
session.close();

$ b / *从记录中删除雇员的方法* /
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession() ;
Transaction tx = null;
尝试{
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();





hibernate.cfg.xml:

 <?xml version =1.0encoding =utf-8?> 
<!DOCTYPE hibernate-configuration PUBLIC
- // Hibernate / Hibernate配置DTD // EN
http://hibernate.sourceforge.net/hibernate-configuration-3.0。 DTD>

< ----->



< - --->

 < hibernate-configuration> 
< session-factory>
< property name =hbm2ddl.auto>更新< / property>
< property name =hibernate.dialect>
org.hibernate.dialect.MySQLDialect
< / property>
< property name =hibernate.connection.driver_class>
com.mysql.jdbc.Driver
< / property>

<! - 假设test是数据库名称 - >
< property name =hibernate.connection.url>
jdbc:mysql:// localhost / test
< / property>
< property name =hibernate.connection.username>
root
< / property>
< property name =hibernate.connection.password>
root
< / property>

<! - XML映射文件列表 - >
< mapping resource =Employee.hbm.xml/>

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

Employee.hbm.xml:

 <?xml version =1.0encoding =utf-8?> 
<!DOCTYPE hibernate-configuration PUBLIC
- // Hibernate / Hibernate配置DTD // EN
http://hibernate.sourceforge.net/hibernate-configuration-3.0。 DTD>

这里我做了修改,但它不起作用

<---
--->

 < hibernate-mapping> 
< class name =com.hb.example.Employeetable =EMPLOYEE>
< meta attribute =class-description>
此类包含员工详细信息。
< / meta>
< id name =idtype =intcolumn =id>
< generator class =native/>
< / id>
< property name =firstNamecolumn =first_nametype =string/>
< property name =lastNamecolumn =last_nametype =string/>
< property name =salarycolumn =salarytype =int/>
< / class>
< / hibernate-mapping>

所以任何一个人都可以帮助我。

解决方案

请参阅第3&第四行在你的休眠配置和映射文件。

DTD的文档说:


Hibernate不会从网上加载DTD文件,但首先从应用程序的类路径中查找
。 DTD文件包含在
hibernate-core.jar中(如果
使用分发包,它也包含在hibernate3.jar中)。

在没有互联网的情况下,你会得到这个例外,因为它大多数情况下会尝试加载DTD文件,用于休眠配置&映射文件,从互联网,在您的应用程序。



当您的应用程序启动&第一次访问hibernate配置文件时,它尝试使用从 www.hibernate.org 下载的DTD文件解析配置文件。



<有关Hiberate DTD的更多信息,请查看以下内容:

http://forum.spring.io/forum/spring-projects/data/73208-how -to-configure-hibernate-cfg-xml-to-work-offline

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/ tutorial.html#tutorial-firstapp-mapping

更新: -

如何使用Hibernate Offline?



对于Hibernate配置文件:


  1. 将您的DTD文件声明更改为



    &l t;!DOCTYPE hibernate-configuration SYSTEMhibernate-configuration-3.0.dtd>


  2. http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&设置它到你的类路径中。

对于hibernate映射文件:




  • 将您的DTD文件声明更改为
    $ b <!DOCTYPE hibernate-configuration SYSTEMhibernate -hpping = 3.0.dtd>


  • 下载hibernate配置DTD文件: http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd &将它设置为你的类路径。


  • 这应该可以正常工作。

    Hi I am new to the hibernate framework.when i am running hibernate sample example code it is working fine if internet connection is available.If internet connection is not available then it is not working and is giving error like below:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Failed to create sessionFactory object.org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
    Exception in thread "main" java.lang.ExceptionInInitializerError
        at com.hb.example.ManageEmployee.main(ManageEmployee.java:20)
    Caused by: org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1411)
        at com.hb.example.ManageEmployee.main(ManageEmployee.java:17)
    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.doConfigure(Configuration.java:1481)
        ... 3 more
    

    My example code will be like below: Employee.java:

    package com.hb.example;
    
    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 com.hb.example;
    
    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(); 
          }
       }
    }
    

    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>
       <property name="hbm2ddl.auto">update</property>
       <property name="hibernate.dialect">
          org.hibernate.dialect.MySQLDialect
       </property>
       <property name="hibernate.connection.driver_class">
          com.mysql.jdbc.Driver
       </property>
    
       <!-- Assume test is the database name -->
       <property name="hibernate.connection.url">
          jdbc:mysql://localhost/test
       </property>
       <property name="hibernate.connection.username">
          root
       </property>
       <property name="hibernate.connection.password">
          root
       </property>
    
       <!-- List of XML mapping files -->
       <mapping resource="Employee.hbm.xml"/>
    
    </session-factory>
    </hibernate-configuration>
    

    Employee.hbm.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">
    

    Here i done the modification but it is not working

    <--- --->

    <hibernate-mapping>
       <class name="com.hb.example.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>
    

    So can any one help please for me.

    解决方案

    See the 3rd & 4th lines in your hibernate configuration & mapping file respectively.

    The document for DTD says:

    Hibernate will not load the DTD file from the web, but first look it up from the classpath of the application. The DTD file is included in hibernate-core.jar (it is also included in the hibernate3.jar, if using the distribution bundle).

    You're getting this exception in absence of Internet because MOSTLY it tries to load DTD files for both hibernate configuration & mapping files, from Internet, in your application.

    When your application is started & the first time it accesses hibernate configuration file it tries to parse the configuration file using its DTD file, which is downloaded from www.hibernate.org.

    For more on Hiberate DTD, please have a look at these:

    http://forum.spring.io/forum/spring-projects/data/73208-how-to-configure-hibernate-cfg-xml-to-work-offline

    http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/tutorial.html#tutorial-firstapp-mapping

    UPDATE :-

    How to work with Hibernate Offline?

    For Hibernate Configuration file:

    1. Change your DTD file declaration to

      <!DOCTYPE hibernate-configuration SYSTEM "hibernate-configuration-3.0.dtd">

    2. Download hibernate configuration DTD file from : http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd & set it to your classpath.

    For hibernate mapping files:

    1. Change your DTD file declaration to

      <!DOCTYPE hibernate-configuration SYSTEM "hibernate-mapping-3.0.dtd">

    2. Download hibernate configuration DTD file from : http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd & set it to your classpath.

    This should work properly.

    这篇关于无法创建sessionFactory object.org.hibernate.HibernateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆