为什么我收到一个映射异常,其根本原因是 SAXParseException;行号:19;列数:45

why am receiving a mapping exception with the root cause as SAXParseException; lineNumber: 19; columnNumber: 45

Buyer.hbm.xml 是买家映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="entity.Buyer" table="buyer">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="username" type="string">
            <column name="username" length="25" not-null="true" unique="true" />
        </property>
        <property name="fname" type="string">
            <column name="fname" length="20" not-null="true" />
        </property>
        <property name="lname" type="string">
            <column name="lname" length="20" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="50" not-null="true" unique="true" />
        </property>
        <property name="phoneno" type="int">
            <column name="phoneno" not-null="true" unique="true" />
        </property>
        <property name="password" type="string">
            <column name="password" length="30" not-null="true" />
        </property>
        <property name="location" type="string">
            <column name="location" length="16" not-null="true" />
        </property>
  </class>
</hibernate-mapping>

Buyer.java 是一个 POJO class,创建为来自 sql 数据库

的实体

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Tariana
 */
@Entity
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Buyer.findAll", query = "SELECT b FROM Buyer b")
    , @NamedQuery(name = "Buyer.findById", query = "SELECT b FROM Buyer b WHERE b.id = :id")
    , @NamedQuery(name = "Buyer.findByUsername", query = "SELECT b FROM Buyer b WHERE b.username = :username")
    , @NamedQuery(name = "Buyer.findByFname", query = "SELECT b FROM Buyer b WHERE b.fname = :fname")
    , @NamedQuery(name = "Buyer.findByLname", query = "SELECT b FROM Buyer b WHERE b.lname = :lname")
    , @NamedQuery(name = "Buyer.findByEmail", query = "SELECT b FROM Buyer b WHERE b.email = :email")
    , @NamedQuery(name = "Buyer.findByPhoneno", query = "SELECT b FROM Buyer b WHERE b.phoneno = :phoneno")
    , @NamedQuery(name = "Buyer.findByPassword", query = "SELECT b FROM Buyer b WHERE b.password = :password")
    , @NamedQuery(name = "Buyer.findByLocation", query = "SELECT b FROM Buyer b WHERE b.location = :location")})
public class Buyer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Integer id;
    @Basic(optional = false)
    private String username;
    @Basic(optional = false)
    private String fname;
    @Basic(optional = false)
    private String lname;
    @Basic(optional = false)
    private String email;
    @Basic(optional = false)
    private int phoneno;
    @Basic(optional = false)
    private String password;
    @Basic(optional = false)
    private String location;

    public Buyer() {
    }

    public Buyer(Integer id) {
        this.id = id;
    }

    public Buyer(Integer id, String username, String fname, String lname, String email, int phoneno, String password, String location) {
        this.id = id;
        this.username = username;
        this.fname = fname;
        this.lname = lname;
        this.email = email;
        this.phoneno = phoneno;
        this.password = password;
        this.location = location;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getPhoneno() {
        return phoneno;
    }

    public void setPhoneno(int phoneno) {
        this.phoneno = phoneno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Buyer)) {
            return false;
        }
        Buyer other = (Buyer) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Buyer[ id=" + id + " ]";
    }
    
}

Registration.java 应该为从 jsp 文件到 sql 数据库

的数据提供持久性

import entity.Buyer;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.*; 
import org.hibernate.boot.registry.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.*;

public class Register extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
        
        Buyer buyerreg = new Buyer();
        
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String username = request.getParameter("username");
        String fname = request.getParameter("fname");
        String lname = request.getParameter("lname");
        String phone = request.getParameter("phoneno");
        int phoneno = Integer.parseInt(phone);
        String location = request.getParameter("location");
        
        buyerreg.setEmail(email);
        buyerreg.setPassword(password);
        buyerreg.setFname(fname);
        buyerreg.setLname(lname);
        buyerreg.setUsername(username);
        buyerreg.setPhoneno(phoneno);
        buyerreg.setLocation(location);
        
        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(Buyer.class)
            .configure();
            
        
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .configure("hibernate.cfg.xml")
                .build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

        SessionFactory factory;  
        factory = meta.getSessionFactoryBuilder().build();
        Session session=factory.openSession();  

        Transaction t = session.beginTransaction();

        session.persist(buyerreg);           
        t.commit();    
        session.close();    
        System.out.println("success"); 
        response.sendRedirect("shop.jsp");
    }
}

hibernate.cfg.xml 是我的休眠配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkulimaonline</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
    <property name="hibernate.connection.autocommit">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping class="entity.Buyer" package="entity" resource="entity/Buyer.hbm.xml"/>
    <property name="annotatedClasses"><list><value>entity.Buyer</value></list>
    </property>
  </session-factory>
</hibernate-configuration>

错误 正在浏览器上显示

message invalid configuration

description The server encountered an internal error that prevented it from fulfilling this request.

exception
org.hibernate.MappingException: invalid configuration
 org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2158)
 org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
 org.hibernate.cfg.Configuration.configure(Configuration.java:2054)
 Register.doGet(Register.java:38)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
 org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
 org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)


root cause
org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 45; Element type "list" must be declared.
 com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
 com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
 com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
 com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:327)
 com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:284)
 com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1906)
 com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:742)
 com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
 com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2784)
 com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
 com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
 com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
 com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
 com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
 com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
 com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
 com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:643)
 org.dom4j.io.SAXReader.read(SAXReader.java:465)
 org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2155)
 org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
 org.hibernate.cfg.Configuration.configure(Configuration.java:2054)
 Register.doGet(Register.java:38)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
 org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
 org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

如您的异常所述,XML 解析器 (SAXParseException) 存在问题。如果您看一下,在定义的 DTD 中,您可以检查元素下是否没有允许的元素。我认为您从 spring 配置中复制了一些内容。

如果您从 hibernate.cfg.xml 文件中删除这些行,将不会显示 SAXParseException:

<property name="annotatedClasses"><list><value>entity.Buyer</value></list>
</property>

我从 hibernate.cfg.xml 文件中删除了带注释的 class。我没有使用 Spring。但不知何故这奏效了 我不知道为什么这段代码不起作用 org.hibernate.MappingException:未知实体:entity.Buyer 这个错误仍然存​​在所以我评论了代码

SessionFactory factory; 
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .configure("hibernate.cfg.xml")
                .build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
        factory = meta.getSessionFactoryBuilder().build();
        Session session=factory.openSession(); 
        
        
        Transaction t = session.beginTransaction();

        session.persist(buyerreg);           
        t.commit();    
        session.close();
        

这是我用的

hibernate.cfg.config

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkulimaonline</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
    <property name="hibernate.connection.autocommit">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
  </session-factory>
</hibernate-configuration>

Registration.java 我评论了不起作用的代码,而这个替代方法不知何故起作用了

import entity.Buyer;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Register extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
        
        Buyer buyerreg = new Buyer();
        
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String username = request.getParameter("username");
        String fname = request.getParameter("fname");
        String lname = request.getParameter("lname");
        String phone = request.getParameter("phoneno");
        int phoneno = Integer.parseInt(phone);
        String location = request.getParameter("location");
        
        buyerreg.setEmail(email);
        buyerreg.setPassword(password);
        buyerreg.setFname(fname);
        buyerreg.setLname(lname);
        buyerreg.setUsername(username);
        buyerreg.setPhoneno(phoneno);
        buyerreg.setLocation(location);
        
        SessionFactory sessionFactory;
        ServiceRegistry serviceRegistry;

        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(Buyer.class)
            .addResource("entity/Buyer.hbm.xml")
            .configure();
        
        serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .configure("hibernate.cfg.xml")
                .build();        
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.persist(buyerreg);
        session.getTransaction().commit();
        session.close();
        
        System.out.println("success"); 
        response.sendRedirect("shop.jsp");
        
        /*SessionFactory factory; 
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .configure("hibernate.cfg.xml")
                .build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
        factory = meta.getSessionFactoryBuilder().build();
        Session session=factory.openSession(); 
        
        
        Transaction t = session.beginTransaction();

        session.persist(buyerreg);           
        t.commit();    
        session.close();
        */
    }
}

Buyer.java 我不得不使用数据库中自动生成的 java class ...我自己的创作有这个错误即使在使用 @Entity 注释 "org.hibernate.MappingException: Unknown entity: entity.Buyer"

之后

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package entity;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Tariana
 */
@Entity
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Buyer.findAll", query = "SELECT b FROM Buyer b")
    , @NamedQuery(name = "Buyer.findById", query = "SELECT b FROM Buyer b WHERE b.id = :id")
    , @NamedQuery(name = "Buyer.findByUsername", query = "SELECT b FROM Buyer b WHERE b.username = :username")
    , @NamedQuery(name = "Buyer.findByFname", query = "SELECT b FROM Buyer b WHERE b.fname = :fname")
    , @NamedQuery(name = "Buyer.findByLname", query = "SELECT b FROM Buyer b WHERE b.lname = :lname")
    , @NamedQuery(name = "Buyer.findByEmail", query = "SELECT b FROM Buyer b WHERE b.email = :email")
    , @NamedQuery(name = "Buyer.findByPhoneno", query = "SELECT b FROM Buyer b WHERE b.phoneno = :phoneno")
    , @NamedQuery(name = "Buyer.findByPassword", query = "SELECT b FROM Buyer b WHERE b.password = :password")
    , @NamedQuery(name = "Buyer.findByLocation", query = "SELECT b FROM Buyer b WHERE b.location = :location")})
public class Buyer implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Integer id;
    @Basic(optional = false)
    private String username;
    @Basic(optional = false)
    private String fname;
    @Basic(optional = false)
    private String lname;
    @Basic(optional = false)
    private String email;
    @Basic(optional = false)
    private int phoneno;
    @Basic(optional = false)
    private String password;
    @Basic(optional = false)
    private String location;

    public Buyer() {
    }

    public Buyer(Integer id) {
        this.id = id;
    }

    public Buyer(Integer id, String username, String fname, String lname, String email, int phoneno, String password, String location) {
        this.id = id;
        this.username = username;
        this.fname = fname;
        this.lname = lname;
        this.email = email;
        this.phoneno = phoneno;
        this.password = password;
        this.location = location;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getPhoneno() {
        return phoneno;
    }

    public void setPhoneno(int phoneno) {
        this.phoneno = phoneno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Buyer)) {
            return false;
        }
        Buyer other = (Buyer) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "entity.Buyer[ id=" + id + " ]";
    }
    
}

Buyer.hbm.xml保持不变

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="entity.Buyer" table="buyer">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="username" type="string">
            <column name="username" length="25" not-null="true" unique="true" />
        </property>
        <property name="fname" type="string">
            <column name="fname" length="20" not-null="true" />
        </property>
        <property name="lname" type="string">
            <column name="lname" length="20" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="50" not-null="true" unique="true" />
        </property>
        <property name="phoneno" type="int">
            <column name="phoneno" not-null="true" unique="true" />
        </property>
        <property name="password" type="string">
            <column name="password" length="30" not-null="true" />
        </property>
        <property name="location" type="string">
            <column name="location" length="16" not-null="true" />
        </property>
  </class>
</hibernate-mapping>