I have this error when I trying to send a GET request to my Spring Boot Application and I don't know what I missed out!
I have this database and I created the JPA Entities and the relationships in Eclipse, with STS (Spring Tool Suite) installed for my Spring Boot Project, accordingly.
The Entities created are:
Categoria.java
package gnammy.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* The persistent class for the categoria database table.
*
*/
#Entity
#Table(name = "categoria")
#NamedQuery(name = "Categoria.findAll", query = "SELECT c FROM Categoria c")
#NamedQuery(name = "Categoria.findByIdRistorante", query = "SELECT DISTINCT c FROM Categoria c INNER JOIN c.portate p INNER JOIN p.ristoranti r WHERE r.idRistorante = :idRistorante")
public class Categoria implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "idCategoria", nullable = false, unique = true, insertable = false, updatable = false)
private int idCategoria;
private String descrizione;
// bi-directional many-to-one association to Portata
#OneToMany(mappedBy = "categoria")
private List<Portata> portate;
public Categoria() {
}
public Categoria(String descrizione) {
super();
this.descrizione = descrizione;
}
public Categoria(int idCategoria, String descrizione) {
super();
this.idCategoria = idCategoria;
this.descrizione = descrizione;
}
public int getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(int idCategoria) {
this.idCategoria = idCategoria;
}
public String getDescrizione() {
return this.descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public List<Portata> getPortate() {
return this.portate;
}
public void setPortate(List<Portata> portatas) {
this.portate = portatas;
}
public Portata addPortata(Portata portata) {
getPortate().add(portata);
portata.setCategoria(this);
return portata;
}
public Portata removePortata(Portata portata) {
getPortate().remove(portata);
portata.setCategoria(null);
return portata;
}
}
Ordine.java
package gnammy.entities;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* The persistent class for the ordine database table.
*
*/
#Entity
#Table(name = "ordine")
#NamedQuery(name = "Ordine.findAll", query = "SELECT o FROM Ordine o")
public class Ordine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "idOrdine", nullable = false, unique = true, insertable = false, updatable = false)
private int idOrdine;
#Column(name = "idRistorante", nullable = false, unique = true, insertable = false, updatable = false)
private int idRistorante;
private String indirizzoConsegna;
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date orarioConsegna;
private String tipoPagamento;
private String note;
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date dataOrdine;
private float totale;
private String cartaDiCredito;
// bi-directional many-to-many association to Portata
#ManyToMany
#JoinTable(name = "ordine_portata", joinColumns = {
#JoinColumn(name = "IdOrdine", referencedColumnName = "IdOrdine") }, inverseJoinColumns = {
#JoinColumn(name = "IdPortata", referencedColumnName = "IdPortata") })
private List<Portata> portate;
// bi-directional many-to-one association to Ristorante
#ManyToOne
#JoinColumn(name = "IdRistorante", referencedColumnName = "IdRistorante")
private Ristorante ristorante;
public Ordine() {
}
public Ordine(int idRistorante, String indirizzoConsegna, Date orarioConsegna, String tipoPagamento, String note,
Date dataOrdine, float totale, String cartaDiCredito) {
super();
this.idRistorante = idRistorante;
this.indirizzoConsegna = indirizzoConsegna;
this.orarioConsegna = orarioConsegna;
this.tipoPagamento = tipoPagamento;
this.note = note;
this.dataOrdine = dataOrdine;
this.totale = totale;
this.cartaDiCredito = cartaDiCredito;
}
public Ordine(int idOrdine, int idRistorante, String indirizzoConsegna, Date orarioConsegna, String tipoPagamento,
String note, Date dataOrdine, float totale, String cartaDiCredito) {
super();
this.idOrdine = idOrdine;
this.idRistorante = idRistorante;
this.indirizzoConsegna = indirizzoConsegna;
this.orarioConsegna = orarioConsegna;
this.tipoPagamento = tipoPagamento;
this.note = note;
this.dataOrdine = dataOrdine;
this.totale = totale;
this.cartaDiCredito = cartaDiCredito;
}
public int getIdOrdine() {
return idOrdine;
}
public void setIdOrdine(int idOrdine) {
this.idOrdine = idOrdine;
}
public int getIdRistorante() {
return idRistorante;
}
public void setIdRistorante(int idRistorante) {
this.idRistorante = idRistorante;
}
public String getCartaDiCredito() {
return this.cartaDiCredito;
}
public void setCartaDiCredito(String cartaDiCredito) {
this.cartaDiCredito = cartaDiCredito;
}
public Date getDataOrdine() {
return this.dataOrdine;
}
public void setDataOrdine(Date dataOrdine) {
this.dataOrdine = dataOrdine;
}
public String getIndirizzoConsegna() {
return this.indirizzoConsegna;
}
public void setIndirizzoConsegna(String indirizzoConsegna) {
this.indirizzoConsegna = indirizzoConsegna;
}
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
public Date getOrarioConsegna() {
return this.orarioConsegna;
}
public void setOrarioConsegna(Date orarioConsegna) {
this.orarioConsegna = orarioConsegna;
}
public String getTipoPagamento() {
return this.tipoPagamento;
}
public void setTipoPagamento(String tipoPagamento) {
this.tipoPagamento = tipoPagamento;
}
public float getTotale() {
return this.totale;
}
public void setTotale(float totale) {
this.totale = totale;
}
public List<Portata> getPortate() {
return this.portate;
}
public void setPortate(List<Portata> portate) {
this.portate = portate;
}
public Ristorante getRistorante() {
return this.ristorante;
}
public void setRistorante(Ristorante ristorante) {
this.ristorante = ristorante;
}
}
Portata.java
package gnammy.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the portata database table.
*
*/
#Entity
#Table(name = "portata")
#NamedQuery(name = "Portata.findAll", query = "SELECT p FROM Portata p")
#NamedQuery(name = "Portata.findByIdRistorante", query = "SELECT DISTINCT p FROM Portata p INNER JOIN p.ristoranti r WHERE r.idRistorante = :idRistorante")
public class Portata implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "idPortata", nullable = false, unique = true, insertable = false, updatable = false)
private int idPortata;
#Column(name = "idCategoria", nullable = false, unique = true, insertable = false, updatable = false)
private int idCategoria;
private String nome;
private String descrizione;
private float prezzo;
// bi-directional many-to-many association to Ordine
#ManyToMany(mappedBy = "portate")
private List<Ordine> ordini;
// bi-directional many-to-one association to Categoria
#ManyToOne
#JoinColumn(name = "IdCategoria", referencedColumnName = "IdCategoria")
private Categoria categoria;
// bi-directional many-to-many association to Ristorante
#ManyToMany(mappedBy = "portate")
private List<Ristorante> ristoranti;
public Portata() {
}
public Portata(int idCategoria, String nome, String descrizione, float prezzo) {
super();
this.idCategoria = idCategoria;
this.nome = nome;
this.descrizione = descrizione;
this.prezzo = prezzo;
}
public Portata(int idPortata, int idCategoria, String nome, String descrizione, float prezzo) {
super();
this.idPortata = idPortata;
this.idCategoria = idCategoria;
this.nome = nome;
this.descrizione = descrizione;
this.prezzo = prezzo;
}
public int getIdPortata() {
return idPortata;
}
public void setIdPortata(int idPortata) {
this.idPortata = idPortata;
}
public int getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(int idCategoria) {
this.idCategoria = idCategoria;
}
public String getDescrizione() {
return this.descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public float getPrezzo() {
return this.prezzo;
}
public void setPrezzo(float prezzo) {
this.prezzo = prezzo;
}
public List<Ordine> getOrdini() {
return this.ordini;
}
public void setOrdini(List<Ordine> ordini) {
this.ordini = ordini;
}
public Categoria getCategoria() {
return this.categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public List<Ristorante> getRistoranti() {
return this.ristoranti;
}
public void setRistoranti(List<Ristorante> ristoranti) {
this.ristoranti = ristoranti;
}
}
Ristorante.java
package gnammy.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* The persistent class for the ristorante database table.
*
*/
#Entity
#Table(name = "ristorante")
#NamedQuery(name = "Ristorante.findAll", query = "SELECT r FROM Ristorante r")
#NamedQuery(name = "Ristorante.findByIdTipoCucina", query = "SELECT DISTINCT r FROM Ristorante r INNER JOIN r.tipiCucina tc WHERE tc.idTipoCucina = :idTipoCucina")
public class Ristorante implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "idRistorante", nullable = false, unique = true, insertable = false, updatable = false)
private int idRistorante;
private String nome;
private String indirizzo;
private String numeroTelefonico;
private String orario;
private float costoDiConsegna;
private float ordineMinimo;
private String linkSito;
// bi-directional many-to-one association to Ordine
#OneToMany(mappedBy = "ristorante")
private List<Ordine> ordini;
// bi-directional many-to-many association to Portata
#ManyToMany
#JoinTable(name = "ristorante_portata", joinColumns = {
#JoinColumn(name = "IdRistorante", referencedColumnName = "IdRistorante") }, inverseJoinColumns = {
#JoinColumn(name = "IdPortata", referencedColumnName = "IdPortata") })
private List<Portata> portate;
// bi-directional many-to-many association to TipoCucina
#ManyToMany
#JoinTable(name = "ristorante_tipo_cucina", joinColumns = {
#JoinColumn(name = "IdRistorante", referencedColumnName = "IdRistorante") }, inverseJoinColumns = {
#JoinColumn(name = "IdTipoCucina", referencedColumnName = "IdTipoCucina") })
private List<TipoCucina> tipiCucina;
public Ristorante() {
}
public Ristorante(String nome, String indirizzo, String numeroTelefonico, String orario, float costoDiConsegna,
float ordineMinimo, String linkSito) {
super();
this.nome = nome;
this.indirizzo = indirizzo;
this.numeroTelefonico = numeroTelefonico;
this.orario = orario;
this.costoDiConsegna = costoDiConsegna;
this.ordineMinimo = ordineMinimo;
this.linkSito = linkSito;
}
public Ristorante(int idRistorante, String nome, String indirizzo, String numeroTelefonico, String orario,
float costoDiConsegna, float ordineMinimo, String linkSito) {
super();
this.idRistorante = idRistorante;
this.nome = nome;
this.indirizzo = indirizzo;
this.numeroTelefonico = numeroTelefonico;
this.orario = orario;
this.costoDiConsegna = costoDiConsegna;
this.ordineMinimo = ordineMinimo;
this.linkSito = linkSito;
}
public int getIdRistorante() {
return idRistorante;
}
public void setIdRistorante(int idRistorante) {
this.idRistorante = idRistorante;
}
public float getCostoDiConsegna() {
return this.costoDiConsegna;
}
public void setCostoDiConsegna(float costoDiConsegna) {
this.costoDiConsegna = costoDiConsegna;
}
public String getIndirizzo() {
return this.indirizzo;
}
public void setIndirizzo(String indirizzo) {
this.indirizzo = indirizzo;
}
public String getLinkSito() {
return this.linkSito;
}
public void setLinkSito(String linkSito) {
this.linkSito = linkSito;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getNumeroTelefonico() {
return this.numeroTelefonico;
}
public void setNumeroTelefonico(String numeroTelefonico) {
this.numeroTelefonico = numeroTelefonico;
}
public String getOrario() {
return this.orario;
}
public void setOrario(String orario) {
this.orario = orario;
}
public float getOrdineMinimo() {
return this.ordineMinimo;
}
public void setOrdineMinimo(float ordineMinimo) {
this.ordineMinimo = ordineMinimo;
}
public List<Ordine> getOrdini() {
return this.ordini;
}
public void setOrdini(List<Ordine> ordini) {
this.ordini = ordini;
}
public Ordine addOrdine(Ordine ordine) {
getOrdini().add(ordine);
ordine.setRistorante(this);
return ordine;
}
public Ordine removeOrdine(Ordine ordine) {
getOrdini().remove(ordine);
ordine.setRistorante(null);
return ordine;
}
public List<Portata> getPortate() {
return this.portate;
}
public void setPortate(List<Portata> portate) {
this.portate = portate;
}
public List<TipoCucina> getTipiCucina() {
return this.tipiCucina;
}
public void setTipiCucina(List<TipoCucina> tipiCucina) {
this.tipiCucina = tipiCucina;
}
}
TipoCucina.java
package gnammy.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the tipo_cucina database table.
*
*/
#Entity
#Table(name = "tipo_cucina")
#NamedQuery(name = "TipoCucina.findAll", query = "SELECT t FROM TipoCucina t")
public class TipoCucina implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "idTipoCucina", nullable = false, unique = true, insertable = false, updatable = false)
private int idTipoCucina;
private String descrizione;
private String immagine;
// bi-directional many-to-many association to Ristorante
#ManyToMany(mappedBy = "tipiCucina")
private List<Ristorante> ristoranti;
public TipoCucina() {
}
public TipoCucina(String descrizione, String immagine) {
super();
this.descrizione = descrizione;
this.immagine = immagine;
}
public TipoCucina(int idTipoCucina, String descrizione, String immagine) {
super();
this.idTipoCucina = idTipoCucina;
this.descrizione = descrizione;
this.immagine = immagine;
}
public int getIdTipoCucina() {
return idTipoCucina;
}
public void setIdTipoCucina(int idTipoCucina) {
this.idTipoCucina = idTipoCucina;
}
public String getDescrizione() {
return this.descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getImmagine() {
return this.immagine;
}
public void setImmagine(String immagine) {
this.immagine = immagine;
}
public List<Ristorante> getRistorantes() {
return this.ristoranti;
}
public void setRistorantes(List<Ristorante> ristorantes) {
this.ristoranti = ristorantes;
}
}
What I missed out???
From the stack trace it is evidentthat the spring jpa is converting your column name incorrectly.
java.sql.SQLSyntaxErrorException: Unknown column 'ristorante0_.id_ristorante' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1020) ~[mysql-connector-java-8.0.15.jar:8.0.15]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.3.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.3.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.getResultSet(Loader.java:2173) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1936) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:937) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2695) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2678) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2512) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.Loader.list(Loader.java:2507) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:396) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:224) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1538) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1561) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1529) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at org.hibernate.query.Query.getResultList(Query.java:165) ~[hibernate-core-5.4.2.Final.jar:5.4.2.Final]
at gnammy.repositories.RistoranteRepositoryImpl.listaRistoranti(RistoranteRepositoryImpl.java:54) ~[classes/:na]
In your stack trace while trying to execute the method listaRistoranti(RistoranteRepositoryImpl.java:54) on the Entity class Ristorante , jpa converts the column name given as #Column(name = "idRistorante") to the camel case id_ristorante ,while in the database the column name is idRistorante itself, which is causing the issue.
From the Configure Hibernate Naming Strategy section of the Spring data access howto guides:
Hibernate uses two different naming strategies to map names from the object model to the corresponding database names. The fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the spring.jpa.hibernate.naming.physical-strategy and spring.jpa.hibernate.naming.implicit-strategy properties, respectively. Alternatively, if ImplicitNamingStrategy or PhysicalNamingStrategy beans are available in the application context, Hibernate will be automatically configured to use them.
By default, Spring Boot configures the physical naming strategy with
SpringPhysicalNamingStrategy. This implementation provides the same
table structure as Hibernate 4: all dots are replaced by underscores
and camel casing is replaced by underscores as well. By default, all
table names are generated in lower case, but it is possible to
override that flag if your schema requires it.
Try using the following property in the application.properties or application.yml whichever you are using, so that spring jpa does not convert your column name and use it as it is specified in your Entity.
Application.yml
spring:
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
I use a framework called "Cuba.Studio" to create a CRUD application.
When I use this JPQL Query, I get this exception:
Error com.haulmont.cuba.core.global.RemoteException: MetaClass not
found for firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK
this is my code:
try (Transaction tx = persistence.createTransaction()) {
EntityManager em = persistence.getEntityManager();
Query query = em.createQuery("select firstusecase$Project.name from
firstusecase$UseCase useCase,
firstusecase$FIRSTUSECASE_USE_CASE_PROJECT_LINK commonTable,
firstusecase$Project project where useCase.id = commonTable.use_case_id
and project.id = commonTable.project_id and useCase.id = :useCaseId")
.setParameter("useCaseId", useCase.getId());
and here is a part of the code of my Entity Class:
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
Does anybody have an idea?
I would be very thankful about your support :)
Thanks
EDIT:
Here is the code of the UseCase Class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Collection;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import com.haulmont.cuba.core.entity.StandardEntity;
import javax.persistence.Column;
import com.haulmont.chile.core.annotations.NamePattern;
import javax.persistence.Lob;
import com.haulmont.chile.core.annotations.MetaProperty;
import javax.persistence.Transient;
#NamePattern("%s|jamaref")
#Table(name = "FIRSTUSECASE_USE_CASE")
#Entity(name = "firstusecase$UseCase")
public class UseCase extends StandardEntity {
private static final long serialVersionUID = 4928397068727365740L;
#Column(name = "JAMAREF", length = 30)
protected String jamaref;
#Column(name = "PROJECT_LIST")
protected String projectList;
#Transient
#MetaProperty
protected String usecaseDescription;
#Column(name = "CHANGE_TRACKING_COMMENT")
protected String changeTrackingComment;
#Lob
#Column(name = "CHANGE_TRACKING")
protected String changeTracking;
#Column(name = "POWERAMSREF", length = 30)
protected String poweramsref;
#Column(name = "LEGACYPWRUC", length = 30)
protected String legacypwruc;
#Column(name = "TRACKING_CHANGE_COMMENT")
protected String trackingChangeComment;
#Column(name = "INSERT_TIMESTAMP")
protected String insertTimestamp;
#Column(name = "USECASE_TYPE")
protected String usecaseType;
#Column(name = "CHANGE_TIMESTAMP")
protected String changeTimestamp;
#JoinTable(name = "FIRSTUSECASE_USE_CASE_PROJECT_LINK",
joinColumns = #JoinColumn(name = "USE_CASE_ID"),
inverseJoinColumns = #JoinColumn(name = "PROJECT_ID"))
#ManyToMany
protected Collection<Project> project;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "USECASE_STATUS_ID")
protected UseCaseStatus usecaseStatus;
public void setProjectList(String projectList) {
this.projectList = projectList;
}
public String getProjectList() {
return projectList;
}
public String getUsecaseDescription() {
return usecaseDescription;
}
public void setChangeTrackingComment(String changeTrackingComment) {
this.changeTrackingComment = changeTrackingComment;
}
public String getChangeTrackingComment() {
return changeTrackingComment;
}
public void setChangeTracking(String changeTracking) {
this.changeTracking = changeTracking;
}
public void setInsertTimestamp(String insertTimestamp) {
this.insertTimestamp = insertTimestamp;
}
public void setChangeTimestamp(String changeTimestamp) {
this.changeTimestamp = changeTimestamp;
}
public String getInsertTimestamp() {
return insertTimestamp;
}
public void setUsecaseType(String usecaseType) {
this.usecaseType = usecaseType;
}
public String getUsecaseType() {
return usecaseType;
}
public String getChangeTimestamp() {
return changeTimestamp;
}
public String getChangeTracking() {
return changeTracking;
}
public void setTrackingChangeComment(String trackingChangeComment) {
this.trackingChangeComment = trackingChangeComment;
}
public String getTrackingChangeComment() {
return trackingChangeComment;
}
public void setUsecaseStatus(UseCaseStatus usecaseStatus) {
this.usecaseStatus = usecaseStatus;
}
public UseCaseStatus getUsecaseStatus() {
return usecaseStatus;
}
public void setJamaref(String jamaref) {
this.jamaref = jamaref;
}
public String getJamaref() {
return jamaref;
}
public void setPoweramsref(String poweramsref) {
this.poweramsref = poweramsref;
}
public String getPoweramsref() {
return poweramsref;
}
public void setLegacypwruc(String legacypwruc) {
this.legacypwruc = legacypwruc;
}
public String getLegacypwruc() {
return legacypwruc;
}
public void setProject(Collection<Project> project) {
this.project = project;
}
public Collection<Project> getProject() {
return project;
}
}
And the code of the Project.class
package com.company.firstusecase.entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Column;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.chile.core.annotations.NamePattern;
#NamePattern("%s|name")
#Table(name = "FIRSTUSECASE_PROJECT")
#Entity(name = "firstusecase$Project")
public class Project extends StandardEntity {
private static final long serialVersionUID = -3997556855391197754L;
#Column(name = "NAME", nullable = false)
protected String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Thanks
I creating "New JPA Controller Classes from Entity Classes" when I press the "FINISH" button and then I get the following error.
Users.java
/*
* 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 com.mycompany.mavenproject1.exceptions.exceptions.exceptions;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
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.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author OZGUR-PC
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id"),
#NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName")})
public class Users 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)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "user_name")
private String userName;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
public Users(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
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;
}
#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 Users)) {
return false;
}
Users other = (Users) 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.mycompany.mavenproject1.exceptions.exceptions.exceptions.Users[ id=" + id + " ]";
}
}
I need ideas on how I can solve it. Thank you in advance for your help.
Make sure you have declared an identifier for your entity. For example let's say there is an entity called Student with identifier as studentId and property name then the entity should be like this, it should have setter and getter methods for your fields:
#Entity
public class Student {
#Id
#GeneratedValue
private int studentId;
private String name;
public String getName() {
return name;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public void setName(String name) {
this.name = name;
}
}
I'm new in Java and I trying to use primefaces datatable to save data in database. I can edit some value in datatable, but after refreshing nothing changed. Here is my code.
User.java
#Entity
#Table(name="users")
public class User {
private int id;
public String name = null;
public String surname = null;
public String username = null;
public String description = null;
public String email = null;
public String phone = null;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
#Column(name = "Name")
public String getName(){
return name;
}
public void setName(String Name){
this.name = Name;
}
#Column(name = "Surname")
public String getSurname(){
return surname;
LogonTest.java
#ViewScoped
#SessionScoped
#javax.faces.bean.ManagedBean(name = "logonTest")
public class LogonTest implements Serializable{
#PersistenceUnit(unitName="Webbeans_RESOURCE_LOCAL")
private EntityManagerFactory emf;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public List<User> userList = new ArrayList();
#PostConstruct
public void init(){
EntityManager em = emf.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("SELECT u FROM User u");
userList = q.getResultList();
System.out.println("Size: " + userList.size());
}
public LogonTest() {
}
}
TableBean.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.RowEditEvent;
#ViewScoped
#javax.faces.bean.ManagedBean(name = "tableBean")
public class TableBean implements Serializable {
private List<User> carsSmall;
public TableBean() {
carsSmall = new ArrayList<User>();
populateRandomCars(carsSmall, 9);
}
private void populateRandomCars(List<User> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new User());
}
public List<User> getCarsSmall() {
return carsSmall;
}
public void onEdit(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Edited", ((User) event.getObject()).getName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public void onCancel(RowEditEvent event) {
FacesMessage msg = new FacesMessage(" Cancelled", ((User) event.getObject()).getName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
I am using TomeEE + MySql and i have problem because function createNamedQuery don't returns any results. I thought that problem is with my
entityManager but i checked in debugMode and is injected.
This is my code:
User Entity:
package pl.gsite.db.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.loginAndPassword", query = "SELECT u FROM User u WHERE u.login = :login and u.password = :password"),
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u WHERE u.login = :login"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "login")
private String login;
#Size(max = 100)
#Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#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 User)) {
return false;
}
User other = (User) 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 "pl.gsite.db.model.User[ id=" + id + " ]";
}
}
My ManagedBean:
package pl.gsite.bean.request;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import pl.gsite.bean.session.LoggedUserBean;
import pl.gsite.db.model.User;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
#Named(value = "loginRequest")
#RequestScoped
public class LoginRequest {
#PersistenceContext(unitName = "gsitePU")
private EntityManager em;
#Inject
private LoggedUserBean loggedUserBean;
private String login;
private String password;
public LoginRequest() {
}
public String authentication() {
try {
List<User> uList = new ArrayList<User>();
TypedQuery qq = em.createNamedQuery("User.findAll", User.class);
uList = qq.getResultList(); // <-- returns empty list
TypedQuery<User> query = em.createNamedQuery("User.loginAndPassword", User.class).setParameter("login", login).setParameter("password", password);
User u = query.getSingleResult(); // <-- throws an NoResultException
this.loggedUserBean.setLoggedUser(u);
}
catch(NoResultException e) {
e.printStackTrace();
}
return "index";
}
/**
* #return the login
*/
public String getLogin() {
return login;
}
/**
* #param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<persistence-unit name="gsitePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>gsite_mysql</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(foreignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
I had the same issue. I changed the jpa persistence from openJPA to eclipseLink. The problem resolved.