#java #hibernate #orm #hibernate-mapping
Вопрос:
Я учусь гибернации и следую точно такому же коду из книги, которой я следую. Я пользуюсь eclipse IDE
и hibernate3
библиотекой. В моей базе данных есть Oracle 11g
только 1 таблица.
Когда я запускаю проект, я получаю следующую ошибку:
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.6
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Sep 03, 2021 11:26:41 AM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : hibtest/Employee.hbm.xml
Failed to create sessionFactory object.org.hibernate.InvalidMappingException: Could not parse mapping document from resource hibtest/Employee.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at hibtest.ManageEmployee.main(ManageEmployee.java:17)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource hibtest/Employee.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:575)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1593)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1561)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1540)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1514)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1434)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1420)
at hibtest.ManageEmployee.main(ManageEmployee.java:14)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:514)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:572)
... 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:505)
... 8 more
Мой класс моделей:
// Employee class
package hibtest;
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;
}
}
// mapping file for Employee class
Hibernate mapping xml file:
<?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="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 выглядит следующим образом:-
<?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="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:@10.92.68.111:1521:MYSCHEMA
</property>
<property name="connection.username">
TESTHIB
</property>
<property name="connection.password">
testhib
</property>
<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
<property name="show_sql">true</property>
<property name="max_fetch_depth">2</property>
<property name="dialect" >
org.hibernate.dialect.Oracle9iDialect
</property>
<property name="jdbc.batch_size">0</property>
<property name="cache.query_cache_factory">
hibernatingrhinos.hibernate.profiler.cache.ProfilerQueryCacheFactory
</property>
<property name="generate_statistics">true</property>
<!-- the only class -->
<mapping resource="hibtest/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
Что я здесь делаю не так?
Столбцы таблицы точно такие же, то есть идентификатор, имя , фамилия и зарплата.
Комментарии:
1. похоже, у вас возникли проблемы с конфигурацией hibernate, не могли бы вы поделиться своим файлом конфигурации hibernate?!
2. Я учусь гибернации , а затем не использую конфигурацию XML. Я использую Hibernate в течение 12 лет, и конфигурация XML уже тогда была устаревшим вариантом. Я никогда не использовал ничего, кроме аннотаций Java.
3. @mr1554 я добавил конфигурацию гибернации, пожалуйста
Ответ №1:
Ваше сопоставление, похоже, в порядке, но, похоже, есть проблема с разрешением DTD.
Hibernate использует DTD для проверки сопоставления XML. DTD извлекается следующим образом: «http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd» URL. В некоторых случаях, когда hibernate не может получить URL-адрес, это приведет к ошибке. Проверьте, может ли ваша система подключиться к URL-адресу. Если приложение не имеет доступа к Интернету, оно должно разрешить DTD с помощью пути к классам. Но если доступ заблокирован, например, через закрытый портал, это может привести к этой ошибке.
Здесь вы можете найти более подробную информацию о сопоставлениях спящего режима: https://docs.jboss.org/hibernate/core/3.2/reference/en/html/mapping.html