inserting a foreign key in child table it showing null everytime - mysql

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.

Related

show details of all orders placed by customer

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.

spring boot mysql JSON request

I want to pass following format while posting time using postmapping. so how can i write model and controller. I am new in spring boot so pls help me.
{
"request":
{
"name":"siva",
"mobile":"9788761376",
"parent":"1",
"description":"aaaa"
}
}
My model and controller
MODEL:
----------
#Entity
#Table(name = "project_category")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"created_date", "updated_date"},
allowGetters = true)
public class ProjectCategoryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotBlank
private String name;
private String description;
private String parent;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public Date getCreatedDate() {
return created_date;
}
public void setCreatedDate(Date created_date) {
this.created_date = created_date;
}
public Date getUpdatedDate() {
return updated_date;
}
public void setUpdatedDate(Date updated_date) {
this.updated_date = updated_date;
}
Controller:
#PostMapping("/project/category/create")
public ResponseEntity createProjectCategory(#Valid #RequestBody
ProjectCategoryModel projectCategory) {
String respId = "project.category.create";
Object dbResp = projectCategoryRepository.save(projectCategory);
ResponseDataBuilder rb = new ResponseDataBuilder();
HashMap<String, Object> respData = new HashMap<String, Object>();
respData.put("id",projectCategory.getId());
respData.put("responseCode", "OK");
respData.put("message","Project Category Created");
respData.put("apiId","project.category.create");
respData.put("ts", new Date(System.currentTimeMillis()));
HashMap<String, Object> responseObj = rb.getResponseData(respId,
respData);
ProjectCategoryResponse response = new ProjectCategoryResponse();
return response.sendResponse(responseObj);
}
=================================================================
===================================================================
In your model class i.e ProjectCategoryModel declare one custom type like Request
Create one class named as Request like this
public class Request{
private String name;
private String description;
private String parent;
private long mobile;
//getter and setter
}
Declare this type in ProjectCategoryModel :
MODEL:
----------
#Entity
#Table(name = "project_category")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"created_date", "updated_date"},
allowGetters = true)
public class ProjectCategoryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private Request request;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date created_date;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updated_date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Request getRequest(){
return request;
}
public void setRequest(Request request){
this.request = request;
}
public Date getCreatedDate() {
return created_date;
}
public void setCreatedDate(Date created_date) {
this.created_date = created_date;
}
public Date getUpdatedDate() {
return updated_date;
}
public void setUpdatedDate(Date updated_date) {
this.updated_date = updated_date;
}

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

How to join two tables and iterate in hibernate

How to write hibernate query to get list with below columns which is executed in mysql query executed in jdbc. How to write HQL query in my Main class please let me know
Parent Entity
#Entity
#Table(name = "parent_info")
public class ParentDTO {
#Id
#GenericGenerator(name = "j", strategy = "increment")
#GeneratedValue(generator = "j")
#Column(name = "P_ID")
private int p_id;
#Column(name = "P_NAME")
private String p_name;
#Column(name = "P_PHONE")
private String p_phone;
#Column(name = "P_EMAIL")
private String p_email;
#Column(name = "REF_ID")
private String ref_id;
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="student_id")
private List<StudentDTO> students;
public List<StudentDTO> getStudents() {
return students;
}
public void setStudents(List<StudentDTO> students) {
this.students = students;
}
public int getP_id() {
return p_id;
}
public void setP_id(int p_id) {
this.p_id = p_id;
}
public String getP_name() {
return p_name;
}
public void setP_name(String p_name) {
this.p_name = p_name;
}
public String getP_phone() {
return p_phone;
}
public void setP_phone(String p_phone) {
this.p_phone = p_phone;
}
public String getP_email() {
return p_email;
}
public void setP_email(String p_email) {
this.p_email = p_email;
}
public String getRef_id() {
return ref_id;
}
public void setRef_id(String ref_id) {
this.ref_id = ref_id;
}
}
Student Entity class
#Entity
#Table(name = "student_info")
public class StudentDTO {
#Id
#GenericGenerator(name = "j", strategy = "increment")
#GeneratedValue(generator = "j")
#Column(name = "S_ID")
private int s_id;
#Column(name = "S_NAME")
private String s_name;
#Column(name = "S_PHONE")
private String s_phone;
#Column(name = "S_EMAIL")
private String s_email;
#Column(name = "REF_ID")
private String ref_id;
#Column(name = "S_CLASS_NAME")
private String s_class_name;
#ManyToOne
#JoinColumn(name="parent_id")
private ParentDTO parent;
public ParentDTO getParent() {
return parent;
}
public void setParent(ParentDTO parent) {
this.parent = parent;
}
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_id;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
public String getS_phone() {
return s_phone;
}
public void setS_phone(String s_phone) {
this.s_phone = s_phone;
}
public String getS_email() {
return s_email;
}
public void setS_email(String s_email) {
this.s_email = s_email;
}
public String getRef_id() {
return ref_id;
}
public void setRef_id(String ref_id) {
this.ref_id = ref_id;
}
public String getS_class_name() {
return s_class_name;
}
public void setS_class_name(String s_class_name) {
this.s_class_name = s_class_name;
}
}
Main class
public class Test {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
List<StudentDTO> groupList = null;
try {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
session.close();
}
}
}
My SQL query executed in jdbc
select pt.P_MOBILE,pt.P_EMAIL, st.S_FIRSTNAME,st.REF_ID from parent_info pt join student_info st on pt.REF_ID = st.REF_ID where st.S_CLASS_TO_JOIN = 10;
String query="paste your query here ";
List<Object[]> objects = session.createSQLQuery(query).list();
ListIterator<Object[]> iterator = objects.listIterator();
while (iterator.hasNext()) {
Object[] object = (Object[]) iterator.next();
int firstcolumn=(Integer) object[0];
int secondcolumn=(Integer) object[1];
}

SPRING+JPA+HIBERNATE Deleting a child deletes the parent object too

I have two tables, Enterprises and Appliance in unidirectional one to many association.
When I try to delete any enterprise, it deletes its corresponding appliances too, which is the expected behavior.
Now if I try to delete any appliance, its corresponding enterprise gets deleted as well!!
This is neither expected nor am I able to figure out how to solve this.
I wish that if I delete an Appliance only that appliance should get deleted not, the Enterprise the appliance belongs too!!
Enterprise Class:
#Entity
#Table(name="Enterprises")
public class Enterprises implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id", nullable=false, unique=true)
private Long id;
#Column(name="EntpName")
private String entpName;
#Column(name="ContactPerson")
private String contactPerson;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="CreatedDate", nullable=false)
private Date createdDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="ModifiedDate")
private Date modifiedDate;
public Enterprises() { }
public Enterprises(Long id) {
this.id = id;
}
public Enterprises(String entpName, String contactPerson) {
this.entpName = entpName;
this.contactPerson = contactPerson;
this.setCreatedDate();
}
// Getter and setter methods
public Long getId() {
return id;
}
public void setId(Long value) {
this.id = value;
}
public String getEntpName() {
return entpName;
}
public void setEntpName(String value) {
this.entpName = value;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String value) {
this.contactPerson = value;
}
public Date getCreatedDate() { return createdDate; }
#PrePersist
public void setCreatedDate() {
this.createdDate = new Date();
}
public Date getModifiedDate() { return modifiedDate; }
#PreUpdate
public void setModifiedDate() {
this.modifiedDate = new Date();
}
}
Appliance Class:
#Entity
#Table(name="Appliance")
public class Appliance {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id", nullable=false, unique=true)
private Long id;
#Column(name="ApplianceName")
private String AppName;
#Column(name="Parameter1")
private String param1;
#Column(name="Parameter2")
private String param2;
#Column(name="Parameter3")
private String param3;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="CreatedDate", nullable=false)
private Date createdDate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="ModifiedDate")
private Date modifiedDate;
#ManyToOne(cascade = {CascadeType.REMOVE, CascadeType.REFRESH}, fetch = FetchType.LAZY)
#JoinColumn(name="Enterprises_id", referencedColumnName = "id")
#OnDelete(action= OnDeleteAction.CASCADE)
private Enterprises enterprise;
public Enterprises getEnterprise() {
return enterprise;
}
public void setEnterprise(Enterprises enterprise) {
this.enterprise = enterprise;
}
// ------------------------
// PUBLIC METHODS
// ------------------------
public Appliance() { }
public Appliance(Long id) {
this.id = id;
}
public Appliance(String AppName, String param1, String param2, String param3) {
this.AppName = AppName;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.setCreatedDate();
}
// Getter and setter methods
public Long getId() {
return id;
}
public void setId(Long value) {
this.id = value;
}
public String getAppName() {
return AppName;
}
public void setAppName(String value) {
this.AppName = value;
}
public String getparam1() {
return param1;
}
public void setparam1(String value) {
this.param1 = value;
}
public String getparam2() {
return param2;
}
public void setparam2(String value) {
this.param2 = value;
}
public String getparam3() {
return param3;
}
public void setparam3(String value) {
this.param3 = value;
}
public Date getCreatedDate() { return createdDate; }
#PrePersist
public void setCreatedDate() {
this.createdDate = new Date();
}
public Date getModifiedDate() { return modifiedDate; }
#PreUpdate
public void setModifiedDate() {
this.modifiedDate = new Date();
}
}
My controller:
ApplianceUserController:
#Controller
#RequestMapping("/")
public class ApplianceUserController {
#Autowired
private ApplianceRepository appliancerepo;
#Autowired
private UserRepository userrepo;
#RequestMapping(value = "{id}/list", method = RequestMethod.GET)
#ResponseBody
public LinkedList<List> listStuff(#PathVariable("id") Enterprises id) {
List<Appliance> appliances = appliancerepo.findApplianceByEnt_id(id);
List<Users> users = userrepo.findUsersByEnt_id(id);
LinkedList<List> together = new LinkedList<List>();
together.add(appliances);
together.add(users);
return together;
}
#RequestMapping(value="{idd}/appliance/add" , method = RequestMethod.POST)
#ResponseBody
Appliance addAppliance(#PathVariable("idd") Enterprises idd , #RequestBody Appliance appliance) {
appliance.setEnterprise(idd);
appliance.setCreatedDate();
return appliancerepo.save(appliance);
}
#RequestMapping(value = "appliance/update/{id}", method = RequestMethod.PUT)
#ResponseBody
Appliance updateAppliance(#PathVariable("id") Long id, #RequestBody Appliance appliance) {
Appliance applianceOld= appliancerepo.findById(id);
applianceOld.setAppName(appliance.getAppName());
applianceOld.setparam1(appliance.getparam1());
applianceOld.setparam2(appliance.getparam2());
applianceOld.setparam3(appliance.getparam3());
applianceOld.setModifiedDate();
return appliancerepo.save(applianceOld);
}
#RequestMapping(value = "appliance/delete/{id}", method = RequestMethod.DELETE)
#ResponseBody
void deleteAppliance(#PathVariable("id") Long id) {
appliancerepo.delete(id);
}
#RequestMapping(value = "appliance/{id}", method = RequestMethod.GET)
#ResponseBody
Appliance getA(#PathVariable("id") Long id) {
Appliance appliance=appliancerepo.findAppliance(id);
System.out.println(appliance);
return appliance;
}
}
PS: Yes, cascade update and delete is ON for the foreign keys in the MySql database!!!!
Please inform me, if you need any other code.
UPDATE:
SOLVED
For future reference by anyone:
Needed to remove the #OnDelete line and and the cascade property from #ManyToOne in the Appliance class!!