HTTP status 500 - Invalid persistence.xml. JPA + Hibernate + DAO + Servlet + JSP

1

This error appears when loading.

  

HTTP status 500 - Invalid persistence.xml.

     

type Exception Report

     

message Invalid persistence.xml.

     

description The server encountered an internal error that caused it not to   I could fill this requirement.

     

exception

     

javax.persistence.PersistenceException: Invalid persistence.xml. Error   parsing XML (line-1: column -1): cvc-elt.1: The   declaration of the element 'persistence'.

     

org.hibernate.ejb.packaging.PersistenceXmlLoader.loadURL (PersistenceXmlLoader.java:147)     org.hibernate.ejb.packaging.PersistenceXmlLoader.deploy (PersistenceXmlLoader.java:171)     org.hibernate.ejb.Ejb3Configuration.configure (Ejb3Configuration.java:324)     org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory (HibernatePersistence.java:56)     javax.persistence.Persistence.createEntityManagerFactory (Persistence.java:63)     javax.persistence.Persistence.createEntityManagerFactory (Persistence.java:47)     dao.ProductoDAO. (ProductoDAO.java:20)     web.servlet.ServletProductos.processRequest (ServletProductos.java:28)     web.servlet.ServletProducts.doGet (ServletProducts.java:102)     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)

Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="JPA_ProductosWebPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.empresa.proyecto.entity.Pedidos</class>
    <class>com.empresa.proyecto.entity.Productos</class>
    <class>com.empresa.proyecto.entity.Pedidosxproducto</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/dbproductos?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value=""/>
    </properties>
  </persistence-unit>
</persistence>

Entity

package com.empresa.proyecto.entity;

import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

@Entity
@Table(name = "productos")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Productos.findAll", query = "SELECT p FROM Productos p"),
    @NamedQuery(name = "Productos.findById", query = "SELECT p FROM Productos p WHERE p.id = :id"),
    @NamedQuery(name = "Productos.findByNombre", query = "SELECT p FROM Productos p WHERE p.nombre = :nombre"),
    @NamedQuery(name = "Productos.findByPreuni", query = "SELECT p FROM Productos p WHERE p.preuni = :preuni")})
public class Productos implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "NOMBRE")
    private String nombre;
    @Basic(optional = false)
    @Column(name = "PREUNI")
    private double preuni;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "productos", fetch = FetchType.LAZY)
    private List<Pedidosxproducto> pedidosxproductoList;

    public Productos() {
    }

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

    public Productos(Integer id, String nombre, double preuni) {
        this.id = id;
        this.nombre = nombre;
        this.preuni = preuni;
    }

    public Integer getId() {
        return id;
    }

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

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public double getPreuni() {
        return preuni;
    }

    public void setPreuni(double preuni) {
        this.preuni = preuni;
    }

    @XmlTransient
    public List<Pedidosxproducto> getPedidosxproductoList() {
        return pedidosxproductoList;
    }

    public void setPedidosxproductoList(List<Pedidosxproducto> pedidosxproductoList) {
        this.pedidosxproductoList = pedidosxproductoList;
    }

    @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 Productos)) {
            return false;
        }
        Productos other = (Productos) 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 "com.empresa.proyecto.entity.Productos[ id=" + id + " ]";
    }

}

DAO

package dao;

import com.empresa.proyecto.entity.Productos;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class ProductoDAO {

    private EntityManagerFactory emf;
    private EntityManager em;

    public ProductoDAO() {
        emf = Persistence.createEntityManagerFactory("JPA_ProductosWebPU");
        em = emf.createEntityManager();
    }

    public List<Productos> productoQRY() {
        Query q = em.createQuery("select productos from Productos productos ");
        return q.getResultList();
    }

    public void productoINS(Productos productos) {
        em.getTransaction().begin();
        em.persist(productos);
        em.getTransaction().commit();
    }

    public void productoUPD(Productos productos) {
        em.getTransaction().begin();
        em.merge(productos);
        em.getTransaction().commit();
    }

    public void productoDEL(Productos productos) {
        em.getTransaction().begin();
        em.remove(productos);
        em.getTransaction().commit();
    }

    public Productos buscarProductoByID(int id) {
        return em.find(Productos.class, id);
    }

}

Servlet

package web.servlet;

import com.empresa.proyecto.entity.Productos;
import dao.ProductoDAO;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ServletProductos", urlPatterns = {"/Productos"})
public class ServletProductos extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");

        String accion = request.getParameter("accion");

        if (accion.equals("QRY")) {

            ProductoDAO productoDAO = new ProductoDAO();
            List<Productos> list = productoDAO.productoQRY();
            request.setAttribute("list", list);
            request.getRequestDispatcher("view/productos/").forward(request, response);

        } else if (accion.equals("INS")) {

            String nom = request.getParameter("nom");
            double pu = Double.parseDouble(request.getParameter("pu"));

            Productos productos = new Productos();
            productos.setNombre(nom);
            productos.setPreuni(pu);

            ProductoDAO productoDAO = new ProductoDAO();
            productoDAO.productoINS(productos);

            List<Productos> list = productoDAO.productoQRY();
            request.setAttribute("list", list);
            request.getRequestDispatcher("view/productos/").forward(request, response);

        } else if (accion.equals("GET")) {

            int id = Integer.parseInt(request.getParameter("id"));
            ProductoDAO productoDAO = new ProductoDAO();
            Productos productos = productoDAO.buscarProductoByID(id);

            request.setAttribute("productos", productos);

            request.getRequestDispatcher("./view/productos/productoUpd.jsp").forward(request, response);

        } else if (accion.equals("UPD")) {

            int id = Integer.parseInt(request.getParameter("id"));
            String nom = request.getParameter("nom");
            double pu = Double.parseDouble(request.getParameter("pu"));

            Productos productos = new Productos(id, nom, pu);

            ProductoDAO productoDAO = new ProductoDAO();
            productoDAO.productoUPD(productos);

            List<Productos> list = productoDAO.productoQRY();
            request.setAttribute("list", list);
            request.getRequestDispatcher("view/productos/").forward(request, response);

        } else if (accion.equals("DEL")) {

            int id = Integer.parseInt(request.getParameter("id"));
            ProductoDAO productoDAO = new ProductoDAO();
            Productos productos = productoDAO.buscarProductoByID(id);

            productoDAO.productoDEL(productos);

            List<Productos> list = productoDAO.productoQRY();
            request.setAttribute("list", list);
            request.getRequestDispatcher("view/productos/").forward(request, response);

        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

JSP

< %@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
< %@page contentType="text/html" pageEncoding="UTF-8"%>
< !DOCTYPE html>
< html>
    < head>
        < meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        < title>JPA 2.0< /title>
    < /head>
    < body>
        < div>
            < table border="1">
                < h1>Lista de Productos</h1>
                < thead>
                    < tr>
                        < td>Código</td>
                        < td>Nombre</td>
                        < td>Precio Unitario</td>
                        < td colspan="2" style="width: 40px">&nbsp;</td>
                    < /tr>
                < /thead>

                < tfoot>
                    < tr>
                        < th colspan="9">JPA 2.0</th>    
                    < /tr>
                < /tfoot>

                < tbody>
                    < c:forEach items="${requestScope.list}" var="producto" >
                        < tr>
                            < td>${producto.id}</td>
                            < td>${producto.nombre}</td>
                            < td>${producto.preuni}</td>
                            < th><a href="./Productos?accion=GET&id=${producto.id}" >Modificar< /a>< /th>
                            < th>< a href="./Productos?accion=DEL&id=${producto.id}" >Eliminar< /a></th>
                        </tr >
                    </c:forEach >
                </tbody >
            </table >

            < p>< a class="simple" href="view/productos/productoIns.jsp">Agregar Producto</a>< /p>
            < p>< a class="simple" href="index.jsp">Home</a></p>
        < /div>
    < /body>
< /html>

If I use EclipseLink it works but I have to use the hibernate libraries

    
asked by Max 11.10.2016 в 00:15
source

1 answer

0

Try the v2.0 and tell me if it works for you:

< persistence version="2.0" 
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">    

I do not know why, but my application with v2.1 does not work for me if I'm not connected to the internet, and instead with v2.0 it does not matter if I have a connection or not.

    
answered by 10.05.2018 в 23:23