IllegalArgumentException: MetaClass not found - mysql

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

Related

java.sql.SQLSyntaxErrorException: Unknown column .JPA Entity Issue?

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

Failed to evaluate Jackson deserialization ,Cannot handle managed/back reference 'defaultReference' (Json)

i have i a class StudentAdmissinAssoDTO that have Other class references
as below
StudentAdmissinAssoDTO
package com.rasvek.cg.entity;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class StudentAdmissinAssoDTO
{
private PrimaryStudentAdmission primaryAdmission;
private StudentDetails studentDetailsDto;
private StudentJoiningDetails studentJoiningDetails;
private StudentPresentClassDetails studentPresentClassDetails;
private StudentGeneralDetails studentGeneralDetails;
private StudentPrevSchoolDetails studentPrevSchoolDetails;
private StudentParentDetails studentParentDetails;
private MasterAddress masterAddress;
private List<AssocFeeStudent> assocFeeStudentId;
public StudentDetails getStudentDetailsDto() {
return studentDetailsDto;
}
public void ListStudentDetailsDto(StudentDetails studentDetailsDto) {
this.studentDetailsDto = studentDetailsDto;
}
public PrimaryStudentAdmission getPrimaryAdmission() {
return primaryAdmission;
}
public void ListPrimaryAdmission(PrimaryStudentAdmission primaryAdmission) {
this.primaryAdmission = primaryAdmission;
}
public StudentJoiningDetails getStudentJoiningDetails() {
return studentJoiningDetails;
}
public void ListStudentJoiningDetails(StudentJoiningDetails studentJoiningDetails) {
this.studentJoiningDetails = studentJoiningDetails;
}
public StudentPresentClassDetails getStudentPresentClassDetails() {
return studentPresentClassDetails;
}
public void ListStudentPresentClassDetails(StudentPresentClassDetails studentPresentClassDetails) {
this.studentPresentClassDetails = studentPresentClassDetails;
}
public StudentGeneralDetails getStudentGeneralDetails() {
return studentGeneralDetails;
}
public void ListStudentGeneralDetails(StudentGeneralDetails studentGeneralDetails) {
this.studentGeneralDetails = studentGeneralDetails;
}
public StudentPrevSchoolDetails getStudentPrevSchoolDetails() {
return studentPrevSchoolDetails;
}
public void ListStudentPrevSchoolDetails(StudentPrevSchoolDetails studentPrevSchoolDetails) {
this.studentPrevSchoolDetails = studentPrevSchoolDetails;
}
public StudentParentDetails getStudentParentDetails() {
return studentParentDetails;
}
public void ListStudentParentDetails(StudentParentDetails studentParentDetails) {
this.studentParentDetails = studentParentDetails;
}
public MasterAddress getMasterAddress() {
return masterAddress;
}
public void ListMasterAddress(MasterAddress masterAddress) {
this.masterAddress = masterAddress;
}
public List<AssocFeeStudent> getAssocFeeStudentId() {
return assocFeeStudentId;
}
public void ListAssocFeeStudentId(List<AssocFeeStudent> assocFeeStudentId) {
this.assocFeeStudentId = assocFeeStudentId;
}
}
and i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter):
[org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]]
please look at MasterAddress
package com.rasvek.cg.entity;
//Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* MasterAddress generated by hbm2java
*/
#Entity
#Table(name = "master_address", catalog = "campus_guru_01")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "addressId")
public class MasterAddress implements java.io.Serializable {
private Integer addressId;
private Integer studentAdmissionId;
private String isSame;
private MasterAddressCountry masterAddressCountry;
private MasterAddressDistrict masterAddressDistrict;
private MasterAddressState masterAddressState;
private String houseNum;
private String streetAddress;
private String citymandal;
private String pincode;
private String addressType;
private Set<AssocStaffAddress> assocStaffAddresses = new HashSet<AssocStaffAddress>(0);
private Set<AssocStudentAddress> assocStudentAddresses = new HashSet<AssocStudentAddress>(0);
public MasterAddress() {
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict,
MasterAddressState masterAddressState) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict, MasterAddressState masterAddressState, String houseNum, String streetAddress, String citymandal, String pincode, String addressType, Set<AssocStaffAddress> assocStaffAddresses, Set<AssocStudentAddress> assocStudentAddresses) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
this.houseNum = houseNum;
this.streetAddress = streetAddress;
this.citymandal = citymandal;
this.pincode = pincode;
this.addressType = addressType;
this.assocStaffAddresses = assocStaffAddresses;
this.assocStudentAddresses = assocStudentAddresses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "address_id", unique = true, nullable = false)
public Integer getAddressId() {
return this.addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "country_id", nullable = false)
public MasterAddressCountry getMasterAddressCountry() {
return this.masterAddressCountry;
}
public void setMasterAddressCountry(MasterAddressCountry masterAddressCountry) {
this.masterAddressCountry = masterAddressCountry;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "district_id", nullable = false)
public MasterAddressDistrict getMasterAddressDistrict() {
return this.masterAddressDistrict;
}
public void setMasterAddressDistrict(MasterAddressDistrict masterAddressDistrict) {
this.masterAddressDistrict = masterAddressDistrict;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "state_id", nullable = false)
public MasterAddressState getMasterAddressState() {
return this.masterAddressState;
}
public void setMasterAddressState(MasterAddressState masterAddressState) {
this.masterAddressState = masterAddressState;
}
#Column(name = "house_num", length = 45)
public String getHouseNum() {
return this.houseNum;
}
public void setHouseNum(String houseNum) {
this.houseNum = houseNum;
}
#Column(name = "street_address", length = 45)
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
#Column(name="citymandal")
public String getCitymandal() {
return this.citymandal;
}
public void setCitymandal(String citymandal) {
this.citymandal = citymandal;
}
#Column(name = "pincode", length = 45)
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
#Column(name = "address_type", length = 9)
public String getAddressType() {
return this.addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStaffAddress> getAssocStaffAddresses() {
return this.assocStaffAddresses;
}
public void setAssocStaffAddresses(Set<AssocStaffAddress> assocStaffAddresses) {
this.assocStaffAddresses = assocStaffAddresses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStudentAddress> getAssocStudentAddresses() {
return this.assocStudentAddresses;
}
public void setAssocStudentAddresses(Set<AssocStudentAddress> assocStudentAddresses) {
this.assocStudentAddresses = assocStudentAddresses;
}
#Column(name="student_admission_id")
public Integer getStudentAdmissionId() {
return studentAdmissionId;
}
public void setStudentAdmissionId(Integer studentAdmissionId) {
this.studentAdmissionId = studentAdmissionId;
}
#Column(name="is_same")
public String getIsSame() {
return isSame;
}
public void setIsSame(String isSame) {
this.isSame = isSame;
}
}
there is no dependency Dependency Between StudentAdmissinAssoDTO and MasterAddress .
i am just using StudentAdmissinAssoDTO to make nested json objects .
so that i can get them in the controller
like bellow
MasterAddress masterAddress =null;
masterAddress = studentAdmissinAssoDTO.getMasterAddress();
why i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter): [org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]
can any one Explain why its happening so. thank you!.
i found my mistake there was i misplace of #JsonManagedReference in MasterDistrict Class of MasterAddress

Mysql duplicated columns with Hibernate parameter name

for the first time, after using Hibernate and EJB in my Java REST web Service, I have noticed that in some tables I have got duplicated columns. If, for example, I have defined the Entity 'Table1' with parameter 'parameterOne' that refers to the column 'parameter_one', now on the table 'Table_1' in the Mysql database I've got the colum 'patameterOne'.
How can i fix this problem?
Yes, ok, i can delete the column from the database, but sometimes the are foreign keys and mysql don't allow me to remove them.
Entity 'Disservizi'
package model;
// Generated 10-feb-2017 16.23.07 by Hibernate Tools 4.0.0.Final
import java.util.Date;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
/**
* Disservizi generated by hbm2java
*/
#Entity
#Table(name = "disservizi")
public class Disservizi implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#OneToMany(mappedBy = "disserviziIdDisservizio", targetEntity = StoricoDisservizi.class)
private Set<StoricoDisservizi> storicoDisservizis;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_disservizio")
private Long idDisservizio;
#Column(name = "stati_disservizio_id_stato_disservizio")
private Long statiDisservizioIdStatoDisservizio;
#ManyToOne
#JoinColumn(name = "categorie_problemi_id_categoria_problema", referencedColumnName = "id_categoria_problema", nullable = true)
private CategorieProblemi categorieProblemiIdCategoriaProblema;
#Column(name = "tempi_ripristino_id_tempo_ripristino")
private Long tempiRipristinoIdTempoRipristino;
#Column(name = "gruppi_owner_id_gruppo_owner")
private Long gruppiOwnerIdGruppoOwner;
#Column(name = "tipi_connessione_id_tipo_connessione")
private Long tipiConnessioneIdTipoConnessione;
#ManyToOne
#JoinColumn(name = "applicativi_impattati_id_applicativo_impattato", referencedColumnName = "id_applicativo_impattato", nullable = true)
private ApplicativiImpattati applicativiImpattatiIdApplicativoImpattato;
#Column(name = "aree_id_area")
private Long areeIdArea;
#Column(name = "numeri_kit_id_numero_kit")
private Long numeriKitIdNumeroKit;
#Column(name = "cause_chiusura_id_causa_chiusura")
private Long causeChiusuraIdCausaChiusura;
#ManyToOne
#JoinColumn(name = "impatti_id_impatto", referencedColumnName = "id_impatto", nullable = true)
private Impatti impattiIdImpatto;
#Column(name = "id_storico_disservizio")
private Long idStoricoDisservizio;
#Column(name = "disservizio")
private String disservizio;
#Column(name = "aggiorna_disservizio")
private String aggiornaDisservizio;
#Column(name = "dettaglio")
private String dettaglio;
#Column(name = "dettaglio_chiusura")
private String dettaglioChiusura;
#Column(name = "preview_sms")
private String previewSms;
#Column(name = "location")
private String location;
#Column(name = "via_stato_disservizio")
private boolean viaStatoDisservizio;
#Column(name = "escalation")
private boolean escalation;
#Column(name = "cliente_in_escalation")
private String clienteInEscalation;
#Column(name = "tecnico_owner")
private String tecnicoOwner;
#Column(name = "data_inizio_disservizio")
private Date dataInizioDisservizio;
#Column(name = "data_chiusura")
private Date dataChiusura;
#Column(name = "body_email")
private String bodyEmail;
#Column(name = "inibizione_dl")
private Boolean inibizioneDl;
#Column(name = "impatti_iniziali_id_impatto_iniziale")
private Long impattiInizialiIdImpattoIniziale;
#Column(name = "zone_disservizio_id_zona_disservizio")
private Long zoneDisservizioIdZonaDisservizio;
#Column(name = "cause_chiusura_sd")
private String causaChiusuraSd;
public Disservizi() {
}
public Long getIdDisservizio() {
return this.idDisservizio;
}
public void setIdDisservizio(Long idDisservizio) {
this.idDisservizio = idDisservizio;
}
public long getStatiDisservizioIdStatoDisservizio() {
return this.statiDisservizioIdStatoDisservizio;
}
public void setStatiDisservizioIdStatoDisservizio(long statiDisservizioIdStatoDisservizio) {
this.statiDisservizioIdStatoDisservizio = statiDisservizioIdStatoDisservizio;
}
public CategorieProblemi getCategorieProblemiIdCategoriaProblema() {
return this.categorieProblemiIdCategoriaProblema;
}
public void setCategorieProblemiIdCategoriaProblema(CategorieProblemi categorieProblemiIdCategoriaProblema) {
this.categorieProblemiIdCategoriaProblema = categorieProblemiIdCategoriaProblema;
}
public Long getTempiRipristinoIdTempoRipristino() {
return this.tempiRipristinoIdTempoRipristino;
}
public void setTempiRipristinoIdTempoRipristino(Long tempiRipristinoIdTempoRipristino) {
this.tempiRipristinoIdTempoRipristino = tempiRipristinoIdTempoRipristino;
}
public Long getGruppiOwnerIdGruppoOwner() {
return this.gruppiOwnerIdGruppoOwner;
}
public void setGruppiOwnerIdGruppoOwner(Long gruppiOwnerIdGruppoOwner) {
this.gruppiOwnerIdGruppoOwner = gruppiOwnerIdGruppoOwner;
}
public Long getTipiConnessioneIdTipoConnessione() {
return this.tipiConnessioneIdTipoConnessione;
}
public void setTipiConnessioneIdTipoConnessione(Long tipiConnessioneIdTipoConnessione) {
this.tipiConnessioneIdTipoConnessione = tipiConnessioneIdTipoConnessione;
}
public ApplicativiImpattati getApplicativiImpattatiIdApplicativoImpattato() {
return this.applicativiImpattatiIdApplicativoImpattato;
}
public void setApplicativiImpattatiIdApplicativoImpattato(ApplicativiImpattati applicativiImpattatiIdApplicativoImpattato) {
this.applicativiImpattatiIdApplicativoImpattato = applicativiImpattatiIdApplicativoImpattato;
}
public Long getAreeIdArea() {
return this.areeIdArea;
}
public void setAreeIdArea(Long areeIdArea) {
this.areeIdArea = areeIdArea;
}
public Long getNumeriKitIdNumeroKit() {
return this.numeriKitIdNumeroKit;
}
public void setNumeriKitIdNumeroKit(Long numeriKitIdNumeroKit) {
this.numeriKitIdNumeroKit = numeriKitIdNumeroKit;
}
public Long getCauseChiusuraIdCausaChiusura() {
return this.causeChiusuraIdCausaChiusura;
}
public void setCauseChiusuraIdCausaChiusura(Long causeChiusuraIdCausaChiusura) {
this.causeChiusuraIdCausaChiusura = causeChiusuraIdCausaChiusura;
}
public Impatti getImpattiIdImpatto() {
return this.impattiIdImpatto;
}
public void setImpattiIdImpatto(Impatti impattiIdImpatto) {
this.impattiIdImpatto = impattiIdImpatto;
}
public Long getIdStoricoDisservizio() {
return this.idStoricoDisservizio;
}
public void setIdStoricoDisservizio(Long idStoricoDisservizio) {
this.idStoricoDisservizio = idStoricoDisservizio;
}
public String getDisservizio() {
return this.disservizio;
}
public void setDisservizio(String disservizio) {
this.disservizio = disservizio;
}
public String getAggiornaDisservizio() {
return this.aggiornaDisservizio;
}
public void setAggiornaDisservizio(String aggiornaDisservizio) {
this.aggiornaDisservizio = aggiornaDisservizio;
}
public String getDettaglio() {
return this.dettaglio;
}
public void setDettaglio(String dettaglio) {
this.dettaglio = dettaglio;
}
public String getDettaglioChiusura() {
return this.dettaglioChiusura;
}
public void setDettaglioChiusura(String dettaglioChiusura) {
this.dettaglioChiusura = dettaglioChiusura;
}
public String getPreviewSms() {
return this.previewSms;
}
public void setPreviewSms(String previewSms) {
this.previewSms = previewSms;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
public boolean isViaStatoDisservizio() {
return this.viaStatoDisservizio;
}
public void setViaStatoDisservizio(boolean viaStatoDisservizio) {
this.viaStatoDisservizio = viaStatoDisservizio;
}
public boolean isEscalation() {
return this.escalation;
}
public void setEscalation(boolean escalation) {
this.escalation = escalation;
}
public String getClienteInEscalation() {
return this.clienteInEscalation;
}
public void setClienteInEscalation(String clienteInEscalation) {
this.clienteInEscalation = clienteInEscalation;
}
public String getTecnicoOwner() {
return this.tecnicoOwner;
}
public void setTecnicoOwner(String tecnicoOwner) {
this.tecnicoOwner = tecnicoOwner;
}
public Date getDataInizioDisservizio() {
return this.dataInizioDisservizio;
}
public void setDataInizioDisservizio(Date dataInizioDisservizio) {
this.dataInizioDisservizio = dataInizioDisservizio;
}
public Date getDataChiusura() {
return this.dataChiusura;
}
public void setDataChiusura(Date dataChiusura) {
this.dataChiusura = dataChiusura;
}
public String getBodyEmail() {
return this.bodyEmail;
}
public void setBodyEmail(String bodyEmail) {
this.bodyEmail = bodyEmail;
}
public Boolean getInibizioneDl() {
return this.inibizioneDl;
}
public void setInibizioneDl(Boolean inibizioneDl) {
this.inibizioneDl = inibizioneDl;
}
public Long getImpattiInizialiIdImpattoIniziale() {
return this.impattiInizialiIdImpattoIniziale;
}
public void setImpattiInizialiIdImpattoIniziale(Long impattiInizialiIdImpattoIniziale) {
this.impattiInizialiIdImpattoIniziale = impattiInizialiIdImpattoIniziale;
}
public Long getZoneDisservizioIdZonaDisservizio() {
return this.zoneDisservizioIdZonaDisservizio;
}
public void setZoneDisservizioIdZonaDisservizio(Long zoneDisservizioIdZonaDisservizio) {
this.zoneDisservizioIdZonaDisservizio = zoneDisservizioIdZonaDisservizio;
}
public String getCausaChiusuraSd() {
return this.causaChiusuraSd;
}
public void setCausaChiusuraSd(String causaChiusuraSd) {
this.causaChiusuraSd = causaChiusuraSd;
}
public Set<StoricoDisservizi> getDisservizis() {
return storicoDisservizis;
}
public void setDisservizis(Set<StoricoDisservizi> storicoDisservizis) {
this.storicoDisservizis = storicoDisservizis;
}
}
The problem is on the parameter impattiIdimpatto. I've got a column with the same name in the DB and I can't remove it because is a foreign key.
In my project I've put the class in the persistence.xml and the file Disservizi.hbm.xml contains the mapping btw property and column name.
Please please help me

HTTP 400 Bad request when calling Rest WebService POST method

Please find the relevant classes and JSON request, I fail to understand what is wrong with my request, I get 400 BAD Request. The request perhaps is not even reaching the server. I dont have a clue whats missing. Appreciate your help on this
Json request payload
{
"campaignID": 1,
"campaignDescription": "A Campaign #1",
"campaignOption": "C",
"countryID": "CI",
"startDateTime": "02/04/2010",
"endDateTime": "02/04/2017",
"channelID": 3,
"lastUpdateBy": "bbblsdcdo",
"lastUpdateTime": "02/04/2017",
"timestamp": "2016-11-10 23:26:10.285",
"campaignIdCRM": null,
"classificationCPC": null,
"formCode": null
}
Campaigns model class
package com.srisris.listload.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name = "Campaigns")
public class Campaigns {
#Id
#Column(name = "CampaignID", nullable = false)
private Integer campaignID;
#Column(name = "CampaignDesc", nullable = false)
private String campaignDescription;
#Column(name = "CampaignOption", nullable = false)
private String campaignOption;
#Column(name = "CountryID", nullable = false)
private String countryID;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "StartDateTime", nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate startDateTime;
// private Date startDateTime;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "EndDateTime", nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private Date endDateTime;
#Column(name = "ChannelID", nullable = false)
private Integer channelID;
#Column(name = "LastUpdateBy", nullable = false)
private String lastUpdateBy;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "LastUpdateTime", nullable = false)
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private Date lastUpdateTime;
private String timestamp;
#Column(name = "CampaignIdCRM", nullable = true)
private String campaignIdCRM;
#Column(name = "ClassificationCPC", nullable = true)
private String classificationCPC;
#Column(name = "FormCode", nullable = true)
private String formCode;
public Campaigns() {
}
public Campaigns(Integer campaignID, String campaignDescription, String campaignOption, String countryID,
LocalDate startDateTime, Date endDateTime, Integer channelID, String lastUpdateBy, Date lastUpdateTime,
String timestamp, String campaignIDCRM, String classificationCPC, String formCode) {
super();
this.campaignID = campaignID;
this.campaignDescription = campaignDescription;
this.campaignOption = campaignOption;
this.countryID = countryID;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.channelID = channelID;
this.lastUpdateBy = lastUpdateBy;
this.lastUpdateTime = lastUpdateTime;
this.timestamp = timestamp;
this.campaignIdCRM = campaignIDCRM;
this.classificationCPC = classificationCPC;
this.formCode = formCode;
}
public Integer getCampaignID() {
return campaignID;
}
public void setCampaignID(Integer campaignID) {
this.campaignID = campaignID;
}
public String getCampaignDescription() {
return campaignDescription;
}
public void setCampaignDescription(String campaignDescription) {
this.campaignDescription = campaignDescription;
}
public String getCampaignOption() {
return campaignOption;
}
public void setCampaignOption(String campaignOption) {
this.campaignOption = campaignOption;
}
public String getCountryID() {
return countryID;
}
public void setCountryID(String countryID) {
this.countryID = countryID;
}
public LocalDate getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(LocalDate startDateTime) {
this.startDateTime = startDateTime;
}
public Date getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public Integer getChannelID() {
return channelID;
}
public void setChannelID(Integer channelID) {
this.channelID = channelID;
}
public String getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(String lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getCampaignIDCRM() {
return campaignIdCRM;
}
public void setCampaignIDCRM(String campaignIDCRM) {
this.campaignIdCRM = campaignIDCRM;
}
public String getClassificationCPC() {
return classificationCPC;
}
public void setClassificationCPC(String classificationCPC) {
this.classificationCPC = classificationCPC;
}
public String getFormCode() {
return formCode;
}
public void setFormCode(String formCode) {
this.formCode = formCode;
}
}
CampaignController class
package com.srisris.listload.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.srisris.listload.domain.Campaigns;
import com.srisris.listload.service.CampaignService;
#RestController
public class CampaignController {
#Autowired
CampaignService campaignService;
#RequestMapping(value = "/campaign/", method = RequestMethod.GET)
public ResponseEntity<List<Campaigns>> listAllCampaigns() {
List<Campaigns> campaigns = campaignService.findAllCampaigns();
if(campaigns.isEmpty()){
return new ResponseEntity<List<Campaigns>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<Campaigns>>(campaigns, HttpStatus.OK);
}
#RequestMapping(value = "/campaign/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Campaigns> getCampaign(#PathVariable("id") Integer id) {
Campaigns campaign = campaignService.findById(id);
if (campaign == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<Campaigns>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Campaigns>(campaign, HttpStatus.OK);
}
#RequestMapping(value = "/campaign/", method = RequestMethod.POST)
public ResponseEntity<Void> createCampaign(#RequestBody Campaigns campaign, UriComponentsBuilder ucBuilder) {
if (campaignService.isCampaignExist(campaign)) {
System.out.println("A Campaign with ID " + campaign.getCampaignID() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
campaignService.saveCampaign(campaign);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/campaign/{id}").buildAndExpand(campaign.getCampaignID()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
#RequestMapping(value = "/campaign/{id}", method = RequestMethod.PUT)
public ResponseEntity<Campaigns> updateCampaign(#PathVariable("id") long id, #RequestBody Campaigns campaign) {
return null;
}
#RequestMapping(value = "/campaign/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Campaigns> deleteCampaign(#PathVariable("id") long id) {
return null;
}
}
Campaign Service Implementation Class
package com.srisris.listload.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.srisris.listload.dao.CampaignDao;
import com.srisris.listload.domain.Campaigns;
#Service("campaignService")
#Transactional
public class CampaignServiceImpl implements CampaignService {
#Autowired
private CampaignDao campaignDao;
private static List<Campaigns> campaigns = new ArrayList<Campaigns>();
// static {
// campaigns = populateDummyCampaigns();
// }
#Override
public List<Campaigns> findAllCampaigns() {
return campaignDao.listAllCampaigns();
}
#Override
public Campaigns findById(Integer id) {
return campaignDao.getCampaign(id);
}
#Override
public void saveCampaign(Campaigns campaign) {
campaignDao.createCampaign(campaign);
}
#Override
public void updateCampaign(Campaigns campaign) {
int index = campaigns.indexOf(campaign);
campaigns.set(index, campaign);
}
#Override
public void deleteCampaign(Integer campaignID) {
for (Iterator<Campaigns> iterator = campaigns.iterator(); iterator.hasNext();) {
Campaigns campaign = iterator.next();
if (campaign.getCampaignID() == campaignID) {
iterator.remove();
}
}
}
public Boolean isCampaignExist(Campaigns campaign) {
return findById(campaign.getCampaignID())!=null;
}
}
It seems issue is with the mapping of the payload json to the POJO Campaigns in the controller. I converted all the Date and LocalDate with String and then tried to map to POJO as below.
I slightly modified your Campaigns POJO:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name = "Campaigns")
public class Campaigns {
#Id
#Column(name = "CampaignID", nullable = false)
private Integer campaignID;
#Column(name = "CampaignDesc", nullable = false)
private String campaignDescription;
#Column(name = "CampaignOption", nullable = false)
private String campaignOption;
#Column(name = "CountryID", nullable = false)
private String countryID;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "StartDateTime", nullable = false)
private String startDateTime;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "EndDateTime", nullable = false)
private String endDateTime;
#Column(name = "ChannelID", nullable = false)
private Integer channelID;
#Column(name = "LastUpdateBy", nullable = false)
private String lastUpdateBy;
#DateTimeFormat(pattern = "dd/MM/yyyy")
#Column(name = "LastUpdateTime", nullable = false)
private String lastUpdateTime;
private String timestamp;
#Column(name = "CampaignIdCRM", nullable = true)
private String campaignIdCRM;
#Column(name = "ClassificationCPC", nullable = true)
private String classificationCPC;
#Column(name = "FormCode", nullable = true)
private String formCode;
public Campaigns() {
}
public Campaigns(Integer campaignID, String campaignDescription, String campaignOption, String countryID, String startDateTime, String endDateTime,
Integer channelID, String lastUpdateBy, String lastUpdateTime, String timestamp, String campaignIDCRM, String classificationCPC, String formCode) {
super();
this.campaignID = campaignID;
this.campaignDescription = campaignDescription;
this.campaignOption = campaignOption;
this.countryID = countryID;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.channelID = channelID;
this.lastUpdateBy = lastUpdateBy;
this.lastUpdateTime = lastUpdateTime;
this.timestamp = timestamp;
this.campaignIdCRM = campaignIDCRM;
this.classificationCPC = classificationCPC;
this.formCode = formCode;
}
public Integer getCampaignID() {
return campaignID;
}
public void setCampaignID(Integer campaignID) {
this.campaignID = campaignID;
}
public String getCampaignDescription() {
return campaignDescription;
}
public void setCampaignDescription(String campaignDescription) {
this.campaignDescription = campaignDescription;
}
public String getCampaignOption() {
return campaignOption;
}
public void setCampaignOption(String campaignOption) {
this.campaignOption = campaignOption;
}
public String getCountryID() {
return countryID;
}
public void setCountryID(String countryID) {
this.countryID = countryID;
}
public String getStartDateTime() {
return startDateTime;
}
public void setStartDateTime(String startDateTime) {
this.startDateTime = startDateTime;
}
public String getEndDateTime() {
return endDateTime;
}
public void setEndDateTime(String endDateTime) {
this.endDateTime = endDateTime;
}
public Integer getChannelID() {
return channelID;
}
public void setChannelID(Integer channelID) {
this.channelID = channelID;
}
public String getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(String lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public String getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(String lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getCampaignIDCRM() {
return campaignIdCRM;
}
public void setCampaignIDCRM(String campaignIDCRM) {
this.campaignIdCRM = campaignIDCRM;
}
public String getClassificationCPC() {
return classificationCPC;
}
public void setClassificationCPC(String classificationCPC) {
this.classificationCPC = classificationCPC;
}
public String getFormCode() {
return formCode;
}
public void setFormCode(String formCode) {
this.formCode = formCode;
}
#Override
public String toString() {
return "CampaignId: " + this.campaignID;
}
}
Driver.java
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
String str = "{\"campaignID\":1,\"campaignDescription\":\"A Campaign #1\",\"campaignOption\":\"C\",\"countryID\":\"CI\",\"startDateTime\":\"02/04/2010\",\"endDateTime\":\"02/04/2017\",\"channelID\":3,\"lastUpdateBy\":\"bbblsdcdo\",\"lastUpdateTime\":\"02/04/2017\",\"timestamp\":\"2016-11-10 23:26:10.285\",\"campaignIdCRM\":null,\"classificationCPC\":null,\"formCode\":null}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Campaigns obj = mapper.readValue(str, Campaigns.class);
System.out.println(obj);
}
I hope this will help you to resolve this problem.

Cannot add or update a child row: a foreign key constraint fails. What's the best practice for mapping multiple onetoone references

I have a Product Entity which has various #OneToOne mapping with Brand, Category and Inventory Entity. Mapping's are given as under.
When I do session.add(product). I get error stating
Cannot add or update a child row: a foreign key constraint fails (test.product_new_1, CONSTRAINT FK42A97DC2A483B29F FOREIGN KEY (PRODUCT_CATEGORY) REFERENCES CATEGORY_NEW_1 (CATEGORY_ID))
To overcome this I did
session.add(category);
session.add(brand);
session.add(inventory);
session.add(product1);
all in one transactional scope.
Should not hibernate take care of related entities like(inventory, category, brand) when an referencing entity is persisted like product ?
Product
#Entity
#Table(name = "PRODUCT_NEW_1")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PRODUCT_ID")
private long id;
#Column(name = "PRODUCT_NAME")
private String productName;
#Column(name = "PRODUCT_DESCRIPTION")
private String productDescription;
#Column(name = "PRODUCT_PRICE")
private Number productPrice;
#Column(name = "PRODUCT_FOR_GENDER")
private char productForGender; // M F U
#Column(name = "PRODUCT_DISCOUNT")
private String productDiscount;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PRODUCT_BRAND")
private Brand brand;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PRODUCT_CATEGORY")
private Category category;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "PRODUCT_INVENTORY")
private Inventory inventory;
// #JoinTable(name = "PRODUCT_CATEGORY", joinColumns = { #JoinColumn(name =
// "PRODUCT_REFERENCE_KEY", nullable = false) }, inverseJoinColumns = {
// #JoinColumn(nullable = false, name = "CATEGORY_REFERENCE_ID") })
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public Number getProductPrice() {
return productPrice;
}
public void setProductPrice(Number productPrice) {
this.productPrice = productPrice;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public char getProductForGender() {
return productForGender;
}
public void setProductForGender(char productForGender) {
this.productForGender = productForGender;
}
public String getProductDiscount() {
return productDiscount;
}
public void setProductDiscount(String productDiscount) {
this.productDiscount = productDiscount;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Brand
package main.java.domain;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="BRAND_NEW")
public class Brand {
#Id
#Column(name = "BRAND_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "BRAND_NAME")
private String brandName;
#Column(name = "BRAND_DESCRIPTION")
private String brandDescription;
#OneToOne(targetEntity=Product.class,mappedBy="brand", cascade=CascadeType.ALL, fetch= FetchType.EAGER)
private Product product;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getBrandDescription() {
return brandDescription;
}
public void setBrandDescription(String brandDescription) {
this.brandDescription = brandDescription;
}
}
Category
package main.java.domain;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "CATEGORY_NEW_1")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CATEGORY_ID")
private long id;
#Column(name = "CATEGORY_NAME")
private String categoryName;
#Column(name = "CATEGORY_DESCRIPTION")
private String categoryDescription;
#OneToOne(targetEntity = Product.class, mappedBy = "category", cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private Product product;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
Inventory
package main.java.domain;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "INVENTORY_NEW")
public class Inventory {
#Id
#Column(name = "INVENTORY_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "QUANT_AVAILABLE")
private long quantityAvailable;
#Column(name = "QUANT_REQUIRED")
private long quantityRequired;
#OneToOne(targetEntity= Product.class, mappedBy = "inventory", cascade=CascadeType.ALL, fetch= FetchType.EAGER)
private Product product;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getQuantityAvailable() {
return quantityAvailable;
}
public void setQuantityAvailable(long quantityAvailable) {
this.quantityAvailable = quantityAvailable;
}
public long getQuantityRequired() {
return quantityRequired;
}
public void setQuantityRequired(long quantityRequired) {
this.quantityRequired = quantityRequired;
}
}
and this is controller that handles addProduct request.
Brand brand = new Brand();
brand.setBrandName("LEVIS");
brand.setBrandDescription("DENIM BRAND OWNED BY ARVIND MILL");
Inventory inventory = new Inventory();
inventory.setQuantityAvailable(5);
inventory.setQuantityRequired(0);
Category category = new Category();
category.setId(10l);
category.setCategoryDescription("ELECTRONICS MOBILE CATEGORY");
category.setCategoryName("Lucida Grande;N;12");
Product product1 = new Product();
product1.setProductDescription("MOTO X SNAP DRAGON 8 MP CAMERA");
product1.setProductDiscount("0");
product1.setProductForGender('U');
product1.setProductPrice(13000);
product1.setProductName("MOTO X 16 GB");
product1.setBrand(brand);
product1.setCategory(category);
product1.setInventory(inventory);
// loginService.add(category,inventory, brand, product1);
loginService.add(product1);
Hibernate will execute one by one query at run time based on our save method order. Because of that only you are getting this error. If you want to give responsibility to hibernate then use 'Cascad' then hibernate will persist all of your child entity first then it will persist main entity.