Java中命名查询的问题

时间:2017-10-19 17:08:49

标签: java hibernate jpa

我有问题。我使用JPA,命名查询和Web Servlet创建了一个动态Web项目。以下是项目的组织方式:

enter image description here

以下是课程:

Auto.java:

package it.ecipar.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Auto {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String marca, modello;

    public Integer getId() {
        return id;
    }

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

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getModello() {
        return modello;
    }

    public void setModello(String modello) {
        this.modello = modello;
    }

}

Hobby.java:

package it.ecipar.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Hobby {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String nome;

    public Integer getId() {
        return id;
    }

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

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

Luogo.java:

package it.ecipar.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Luogo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String nome;

    public Integer getId() {
        return id;
    }

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

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

}

Persona.java:

package it.ecipar.model;

import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;


@NamedQueries({
    @NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")
})

@Entity
public class Persona {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String nome, cognome;

    private Date dataDiNascita;

    @OneToMany
    private List<Auto> auto;

    @ManyToMany
    private List<Hobby> hobby;

    @ManyToOne
    private Luogo luogoDiNascita;

    public Integer getId() {
        return id;
    }

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

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCognome() {
        return cognome;
    }

    public void setCognome(String cognome) {
        this.cognome = cognome;
    }

    public List<Auto> getAuto() {
        return auto;
    }

    public void setAuto(List<Auto> auto) {
        this.auto = auto;
    }

    public List<Hobby> getHobby() {
        return hobby;
    }

    public void setHobby(List<Hobby> hobby) {
        this.hobby = hobby;
    }

    public Luogo getLuogoDiNascita() {
        return luogoDiNascita;
    }

    public void setLuogoDiNascita(Luogo luogoDiNascita) {
        this.luogoDiNascita = luogoDiNascita;
    }

    public Date getDataDiNascita() {
        return dataDiNascita;
    }

    public void setDataDiNascita(Date dataDiNascita) {
        this.dataDiNascita = dataDiNascita;
    }

}

JPAUtil.java:

package it.ecipar.common;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class JPAUtil {

    private static EntityManagerFactory emf;
    private EntityManager em;

    public JPAUtil() {
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("MyProject");
        }
        em = emf.createEntityManager();
    }

    public Object insert(Object o) {
        em.getTransaction().begin();
        em.persist(o);
        em.getTransaction().commit();

        return o;
    }

    public Object update(Object o) {
        em.getTransaction().begin();
        Object res = em.merge(o);
        em.getTransaction().commit();

        return res;
    }

    public void delete(Object o) {
        em.getTransaction().begin();
        em.remove(em.contains(o) ? o : em.merge(o));
        em.getTransaction().commit();
    }

    public Object load(Class<?> c, Integer id) {
        return em.find(c, id);
    }

    public List<?> runNamedQuery(String name, HashMap<String, Object> params) {
        Query query = em.createNamedQuery(name);
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String k : keys) {
                query.setParameter(k, params.get(k));
            }
        }

        return query.getResultList();
    }

    public Query createQuery(String q) {
        return em.createQuery(q);
    }

    public void close() {
        em.close();
    }

    public void closeFactory() {
        emf.close();
    }
}

Demo.java:

package it.ecipar.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import it.ecipar.model.Auto;
import it.ecipar.model.Hobby;
import it.ecipar.model.Luogo;
import it.ecipar.model.Persona;

public class Demo {

    public static void main(String[] args) {
        JPAUtil u = new JPAUtil();

        for(int i = 0; i < 10; i++) {
            save(u, i, i + 1);
        }

        u.close();
        u.closeFactory();
    }

    public static void save(JPAUtil u, int i, int numAuto) {

        Luogo l = new Luogo();
        l.setNome("nome luogo " + i);
        u.insert(l);

        List<Hobby> listaHobby = new ArrayList<>();
        Hobby h = new Hobby();
        h.setNome("nome hobby " + i);
        u.insert(h);
        listaHobby.add(h);

        List<Auto> listaAuto = new ArrayList<>();
        for (int j = i; j < i + numAuto; j++) {
            Auto a = new Auto();
            a.setMarca("marca " + j);
            a.setModello("modello " + j);

            u.insert(a);

            listaAuto.add(a);
        }

        Calendar cal = GregorianCalendar.getInstance();
        cal.add(Calendar.YEAR, -20 * i);

        Persona p = new Persona();
        p.setNome("nome " + i);
        p.setCognome("cognome " + i);
        p.setDataDiNascita(cal.getTime());
        p.setHobby(listaHobby);
        p.setLuogoDiNascita(l);
        p.setAuto(listaAuto);

        u.insert(p);
    }
}

这是persistence.xml文件:

<persistence 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"
             version="2.1">

    <persistence-unit name="MyProject" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <class>it.ecipar.model.Auto</class>
        <class>it.ecipar.model.Hobby</class>
        <class>it.ecipar.model.Luogo</class>
        <class>it.ecipar.model.Persona</class>
        <properties>
        <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/persone"/>
          <property name="hibernate.connection.username" value="postgres" />
            <property name="hibernate.connection.password" value="postgres" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/> 
            <property name="hibernate.show_sql" value="true" /> <!-- Show SQL in console -->
            <property name="hibernate.format_sql" value="true" />
    </properties>
    </persistence-unit>
</persistence>

这是PersonaServlet.java:

package it.ecipar.web;

import java.io.IOException;
import java.io.PrintWriter;
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;

import flexjson.JSONSerializer;
import it.ecipar.common.JPAUtil;
import it.ecipar.model.Persona;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/persone" })
public class PersonaServlet extends HttpServlet {



    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");
        String json = null;

        if (id == null) {

            System.out.println("Ciao");
            @SuppressWarnings("unchecked")
            List<Persona> list = (List<Persona>) new JPAUtil().runNamedQuery("personalista",null);
            JSONSerializer js = new JSONSerializer();
            json = js.include("auto").include("hobby").serialize(list);
        } else {
            Persona p = (Persona) new JPAUtil().load(Persona.class, Integer.valueOf(id));
            JSONSerializer js = new JSONSerializer();
            json = js.include("auto").include("hobby").serialize(p);
        }

        resp.setContentType("application/json");

        PrintWriter w = resp.getWriter();
        w.print(json);
        w.flush();
    }
}

当我运行程序时,它会给我一个后续错误:

Exception in thread "main" javax.persistence.PersistenceException: Unable to build entity manager factory
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at it.ecipar.common.JPAUtil.<init>(JPAUtil.java:19)
    at it.ecipar.common.Demo.main(Demo.java:16)
Caused by: org.hibernate.HibernateException: Errors in named queries: persona.lista
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:545)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
    ... 5 more

有人可以帮我吗?感谢。

1 个答案:

答案 0 :(得分:1)

您的查询

 @NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")

有错误。您有Persona o,但按p.cognome...排序。您需要使用相同的表引用:

 @NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by o.cognome, o.nome")