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
Related
I am inserting a foreign key in a child table using a #OnetoMany relationship between parent and medicine. One parent has many medicines and it shows me null.
I have done many searches for my problem and I have tried every possible solution, but it's not working.
Parent Class
#Entity
#Table(name = "patient_domain")
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "p_id")
private Integer p_id;
#Column(name = "doctor_name")
private String doctor_name;
#Column(name="name")
private String name;
#Column(name="hospital_clinic")
private String hospital_clinic;
#Column(name="date")
private Date date;
#OneToMany(mappedBy = "patient", cascade = CascadeType.ALL)
private List<Medicine> medicines;
Patient Bean class
package com.gamification.beans;
import com.gamification.entities.Medicine;
import java.util.Date;
import java.util.List;
public class PatientBean {
private Integer p_id;
private String name;
private String doctor_name;
private Date date;
private List<Medicine> medicines;
public List<Medicine> getMedicines() {
return medicines;
}
public void setMedicines(List<Medicine> medicines) {
this.medicines = medicines;
}
public Integer getP_id() {
return p_id;
}
public void setP_id(Integer p_id) {
this.p_id = p_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDoctor_name() {
return doctor_name;
}
public void setDoctor_name(String doctor_name) {
this.doctor_name = doctor_name;
}
public String getHospital_clinic() {
return hospital_clinic;
}
public void setHospital_clinic(String hospital_clinic) {
this.hospital_clinic = hospital_clinic;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
private String hospital_clinic;
}
Medicine Class
#Entity
#Table(name = "medicine_kit")
public class Medicine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "med_id")
private Integer med_id;
#Column(name="med_name")
private String med_name;
#Column(name="med_type")
private String med_type;
#Column(name="med_quantity")
private String med_quantity;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "patient_domain_p_id", nullable = false,
referencedColumnName = "p_id")
private Patient patient;
MedicineBean
public class MedicineBean {
private Integer med_id;
private String med_name;
private String med_type;
private String med_quantity;
private Integer patientid;
public Integer getPatientid() {
return patientid;
}
public void setPatientid(Integer patientid) {
this.patientid = patientid;
}
public Integer getMed_id() {
return med_id;
}
public void setMed_id(Integer med_id) {
this.med_id = med_id;
}
public String getMed_name() {
return med_name;
}
public void setMed_name(String med_name) {
this.med_name = med_name;
}
public String getMed_type() {
return med_type;
}
public void setMed_type(String med_type) {
this.med_type = med_type;
}
public String getMed_quantity() {
return med_quantity;
}
public void setMed_quantity(String med_quantity) {
this.med_quantity = med_quantity;
}
}
PatientController
#RequestMapping(method = {RequestMethod.POST})
public ResponseEntity<ApiResponse> createOrUpdateUser(#RequestBody PatientBean patientBean) throws Exception {
ApiResponse status = new ApiResponse();
status.setStatus(false);
status.setMessage("please select record");
try {
if(patientBean != null) {
Patient patient = new Patient();
List<Medicine> listmedicine=new ArrayList<Medicine>();
status.setStatus(true);
if(patientBean.getP_id() != null) {
patient.setP_id(patientBean.getP_id());
status.setMessage("Successfully record updated");
} else {
status.setMessage("Successfully record created");
}
patient.setName(patientBean.getName());
patient.setDoctor_name(patientBean.getDoctor_name());
patient.setHospital_clinic(patientBean.getHospital_clinic());
patient.setDate(CommonUtil.getCurrentTimestamp());
if(patient.getMedicines().size()>0)
{
for (int i=0;i<patient.getMedicines().size();i++)
{
Medicine medicine=new Medicine();
medicine.setMed_name(patientBean.getMedicines().get(i).getMed_name());
medicine.setMed_quantity(patientBean.getMedicines().get(i).getMed_quantity());
medicine.setMed_type(patientBean.getMedicines().get(i).getMed_type());
medicine.setPatient(patient);
listmedicine.add(medicine);
}
}
patient.setMedicines(listmedicine);
status.getResponseList().add(patient);
patienServiceImp.createPatient(patient);
}
return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
} catch (Exception e) {
status.setStatus(false);
status.setMessage("Something went wrong on server");
MyPrint.println(e.getMessage());
return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
}
}
solved, I got the mistake that i didn't set the medicine in the patient,
"patient.setMedicines(patientBean.getMedicines());" just add this one in my code and my code is working properly.
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
I am developing an E-Commerce website(Spring MVC, java, mySql, Hibernate) for my college project. I have various models like customer,product,orders,custOrderHistory, etc.
I am able to show all customer details(in admin page) and all products for a customer to browse through.
But the problem I am facing is, how do I show the Orders and order history of a customer?
My orders table has orderId, productId, quantity and total price. but to show the product name, I have to use the productId and rerieve the Product name from product table.
I have no clue on how to do it.
Till now, i was using the jstl foreach loop to iterate the products in the productList.jsp page and displaying them in a table.
But as i told above, i need to retrieve data from 3-4 tables at once, like productName(from product table), productManuacturer(also from product table), ShippingAddress (from customer table). And I am unsure how to do this.
Edit 1: I asked this question from someone else's computer and didn't have my code with me then.
So, I am giving my code here.
Customer.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = -3280023076408333682L;
#Id
#GeneratedValue
private int customerId;
#NotEmpty(message = " The customer name must not be blank.")
private String customerName;
#NotEmpty (message = " The customer email must not be blank.")
private String customerEmail;
private String customerPhone;
#NotEmpty (message = " The username must not be blank.")
private String username;
#NotEmpty (message = " The password must not be blank.")
private String password;
private boolean enabled;
#OneToOne
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
#OneToOne()
#JoinColumn(name = "cartId")
#JsonIgnore
private Cart cart;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
}
Cart.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Cart implements Serializable{
private static final long serialVersionUID = -2479653100535233857L;
#Id
#GeneratedValue
private int cartId;
#OneToMany(mappedBy = "cart", cascade= CascadeType.ALL, fetch = FetchType.EAGER)
private List cartItems = new ArrayList();
#OneToOne
#JoinColumn(name = "customerId")
#JsonIgnore
private Customer customer;
private double grandTotal;
public int getCartId() {
return cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public double getGrandTotal() {
return grandTotal;
}
public void setGrandTotal(double grandTotal) {
this.grandTotal = grandTotal;
}
public List getCartItems() {
return cartItems;
}
public void setCartItems(List cartItems) {
this.cartItems = cartItems;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
CartItem.java
package com.site.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
#Entity
public class CartItem implements Serializable{
private static final long serialVersionUID = -904360230041854157L;
#Id
#GeneratedValue
private int cartItemId;
#ManyToOne
#JoinColumn(name="cartId")
#JsonIgnore
private Cart cart;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
private int quantity;
private double totalPrice;
#ManyToMany(cascade=CascadeType.ALL, mappedBy="cartItems")
#JsonIgnore
private List<OrderHistory> orderHistoryList;
public int getCartItemId() {
return cartItemId;
}
public void setCartItemId(int cartItemId) {
this.cartItemId = cartItemId;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public List<OrderHistory> getOrderHistoryList() {
return orderHistoryList;
}
public void setOrderHistoryList(List<OrderHistory> orderHistoryList) {
this.orderHistoryList = orderHistoryList;
}
}
CustomerOrder.java
package com.site.model;
import javax.persistence.*;
import java.io.Serializable;
#Entity
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = -3608286390950243118L;
#Id
#GeneratedValue
private int customerOrderId;
#OneToOne
#JoinColumn(name = "cartId")
private Cart cart;
#OneToOne
#JoinColumn(name = "customerId")
private Customer customer;
#OneToOne
#JoinColumn(name = "billingAddressId")
private BillingAddress billingAddress;
#OneToOne
#JoinColumn(name = "shippingAddressId")
private ShippingAddress shippingAddress;
public int getCustomerOrderId() {
return customerOrderId;
}
public void setCustomerOrderId(int customerOrderId) {
this.customerOrderId = customerOrderId;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public BillingAddress getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(BillingAddress billingAddress) {
this.billingAddress = billingAddress;
}
public ShippingAddress getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(ShippingAddress shippingAddress) {
this.shippingAddress = shippingAddress;
}
}
OrderHistory.java
package com.site.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
#Entity
public class OrderHistory implements Serializable {
private static final long serialVersionUID = 1083533250613139445L;
#Id
#GeneratedValue
private int orderHistoryId;
private int customerId;
private String customerName;
private int customerOrderId;
private int cartId;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "cartItem_orderHistory", joinColumns = #JoinColumn(name = "orderHistoryId"),
inverseJoinColumns = #JoinColumn
(name = "cartItemId"))
private List<CartItem> cartItems = new ArrayList<CartItem>();
private double grandTotal;
private String billingAddress;
private String shippingAddress;
public int getOrderHistoryId() {
return orderHistoryId;
}
public void setOrderHistoryId(int orderHistoryId) {
this.orderHistoryId = orderHistoryId;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public int getCustomerOrderId() {
return customerOrderId;
}
public void setCustomerOrderId(int customerOrderId) {
this.customerOrderId = customerOrderId;
}
public int getCartId() {
return cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
public double getGrandTotal() {
return grandTotal;
}
public void setGrandTotal(double grandTotal) {
this.grandTotal = grandTotal;
}
public String getBillingAddress() {
return billingAddress;
}
public void setBillingAddress(String billingAddress) {
this.billingAddress = billingAddress;
}
public String getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(String shippingAddress) {
this.shippingAddress = shippingAddress;
}
}
edit 2: how do I store the data in the ustomerorder table and orderhistory table, and also, how do i show it on a jsp page?
you should have a CustomerId column in order table for detecting the order is associated with which customer. Simply insert logged in userid in that and fetch the customer name by making join with customer table.
You should have customerid in your order table. So that you can fetch the customer's order history by providing customerid.
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
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.