Содержимое элемента типа "id" должно совпадать - hbm xml
Я знаю, что этот вопрос задают довольно часто.
Я получаю приведенную ниже ошибку отображения.
Я попробовал некоторые перестановки и комбинации.
Я пробовал некоторые решения и не могу исправить это.
Может кто-нибудь посмотреть на мою ниже конфигурацию?
Xmls действительны.
Я использую Hibernate 3 и MySQL в качестве базы данных
Журнал ошибок:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/sample/Employee.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.sample.SessionFactoryUtil.<clinit>(SessionFactoryUtil.java:17)
at com.sample.TestEmployee.main(TestEmployee.java:13)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/sample/Employee.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:523)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1511)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1479)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1458)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1432)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1352)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1338)
at com.sample.SessionFactoryUtil.<clinit>(SessionFactoryUtil.java:12)
... 1 more
Caused by: org.hibernate.MappingException: invalid mapping
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:463)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:520)
... 8 more
Caused by: org.xml.sax.SAXParseException: The content of element type "id" must match "(meta*,column*,type?,generator?)".
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:460)
... 9 more
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "//Hibernate/Hibernate Mapping DTD 3.0//EN/" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.sample.Employee" table="employee">
<id name="idEmployee" column="ID">
<column name="uid" not-null="true"/>
<generator class="native" />
</id>
<property name="empName">
<column name="empName" length="16" not-null="true" />
</property>
<property name="sex">
<column name="sex" length="16" not-null="true" />
</property>
</class>
</hibernate-mapping>
Employee class:
package com.sample;
public class Employee {
private Long idEmployee;
private String empName;
private String sex;
public Long getIdEmployee() {
return idEmployee;
}
public void setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
}
public String getEmpName() {
return empName;
}
private String address;
private int age;
public void setEmpName(String empName) {
this.empName = empName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
CREATE TABLE `employee` (
`idEmployee` int(11) NOT NULL AUTO_INCREMENT,
`empName` varchar(45) NOT NULL,
`sex` varchar(45) NOT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idEmployee`)
);
2 ответа
Исключение говорит:
Caused by: org.xml.sax.SAXParseException: The content of element type "id" must match "(meta*,column*,type?,generator?)".
Ваш тип удостоверения личности не соответствует. На Employee
класс ваш idEmployee
тип переменной Long
и в файле.hbm.xml ваше сопоставление свойств идентификатора имеет native
генератор, который означает, что идентификатор Integer
введите по умолчанию. Так что вы должны использовать type="long"
аннотации на вашу собственность ID. Или просто попробуйте использовать другой тип генератора идентификаторов. И на вашей аннотации ID в файле.hbm.xml вы используете два имени для столбца ID. Ты используешь column="ID"
а также column="uid"
, Пример того, как должен выглядеть файл.hbm.xml:
<hibernate-mapping>
<class name="com.sample.Employee" table="employee">
<id name="idEmployee" type="long">
<column name="uid" not-null="true"/>
<generator class="native" />
</id>
<property name="empName">
<column name="empName" length="16" not-null="true" />
</property>
<property name="sex">
<column name="sex" length="16" not-null="true" />
</property>
</class>
</hibernate-mapping>
Или попробуйте использовать SequenceStyleGenerator
, Генератор, который создает отдельную последовательность идентификаторов для каждой таблицы по заданному имени последовательности. Тип сгенерированного идентификатора по умолчанию Long
, Пример файла.hbm.xml:
<hibernate-mapping>
<class name="com.sample.Employee" table="employee">
<id name="idEmployee" column="ID">
<generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
<param name="optimizer">none</param>
<param name="increment_size">1</param>
<param name="sequence_name">seq_employee_id</param>
</generator>
</id>
<property name="empName">
<column name="empName" length="16" not-null="true" />
</property>
<property name="sex">
<column name="sex" length="16" not-null="true" />
</property>
</class>
</hibernate-mapping>
Я надеюсь, что это поможет вам... ☺
Я думаю, что вы пропустите сопоставление для атрибутов "адрес" и "возраст". Почему ты их не сделал? И проверьте теги длины, которые вы используете, почему они все равны 16?
Попробуй это:
<hibernate-mapping>
<class name="com.sample.Employee" table="employee">
<id name="idEmployee" column="ID">
<generator class="native" />
</id>
<property name="empName" column="empName"></property>
<property name="sex" column="sex"></property>
<property name="address" column="address"></property>
<property name="age" column="age"></property>
</class>
</hibernate-mapping>