Excluding properties from JSON processing in Struts2 - json

I have the following (full) entity class.
public class StateTable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "state_id", nullable = false)
private Long stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<UserTable> userTableSet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<City> citySet;
#OneToMany(mappedBy = "stateId", fetch = FetchType.LAZY)
private Set<Inquiry> inquirySet;
#OneToMany(mappedBy = "shippingState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet;
#OneToMany(mappedBy = "paymentState", fetch = FetchType.LAZY)
private Set<OrderTable> orderTableSet1;
#JoinColumn(name = "country_id", referencedColumnName = "country_id")
#ManyToOne(fetch = FetchType.LAZY)
private Country countryId;
public StateTable() {
}
public StateTable(Long stateId) {
this.stateId = stateId;
}
public Long getStateId() {
return stateId;
}
public void setStateId(Long stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
#XmlTransient
public Set<UserTable> getUserTableSet() {
return userTableSet;
}
public void setUserTableSet(Set<UserTable> userTableSet) {
this.userTableSet = userTableSet;
}
#XmlTransient
public Set<City> getCitySet() {
return citySet;
}
public void setCitySet(Set<City> citySet) {
this.citySet = citySet;
}
#XmlTransient
public Set<Inquiry> getInquirySet() {
return inquirySet;
}
public void setInquirySet(Set<Inquiry> inquirySet) {
this.inquirySet = inquirySet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet() {
return orderTableSet;
}
public void setOrderTableSet(Set<OrderTable> orderTableSet) {
this.orderTableSet = orderTableSet;
}
#XmlTransient
public Set<OrderTable> getOrderTableSet1() {
return orderTableSet1;
}
public void setOrderTableSet1(Set<OrderTable> orderTableSet1) {
this.orderTableSet1 = orderTableSet1;
}
public Country getCountryId() {
return countryId;
}
public void setCountryId(Country countryId) {
this.countryId = countryId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (stateId != null ? stateId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StateTable)) {
return false;
}
StateTable other = (StateTable) object;
if ((this.stateId == null && other.stateId != null) || (this.stateId != null && !this.stateId.equals(other.stateId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.StateTable[ stateId=" + stateId + " ]";
}
}
I need only two properties from this class as a JSON response namely, stateId and stateName. The rest of the properties must be ignored from being processed/serialized by JSON.
I have tried to set json.excludeProperties to the json interceptor as follows.
#Namespace("/admin_side")
#ResultPath("/WEB-INF/content")
#ParentPackage(value="json-default")
public final class StateListAction extends ActionSupport implements Serializable, ValidationAware
{
#Autowired
private final transient SharableService sharableService=null;
private static final long serialVersionUID = 1L;
private Long id;
List<StateTable>stateTables=new ArrayList<StateTable>();
public StateListAction() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JSON(name="stateTables")
public List<StateTable> getStateTables() {
return stateTables;
}
public void setStateTables(List<StateTable> stateTables) {
this.stateTables = stateTables;
}
#Action(value = "PopulateStateList",
results = {
#Result(type="json", name=ActionSupport.SUCCESS, params={"json.enableSMD", "true", "json.enableGZIP", "true", "json.excludeNullProperties", "true", "json.root", "stateTables", "json.excludeProperties", "userTableSet, citySet, inquirySet, orderTableSet, orderTableSet1, countryId", "validation.validateAnnotatedMethodOnly", "true"})})
public String populateStateList() throws Exception
{
System.out.println("countryId = "+id);
stateTables=sharableService.findStatesByCountryId(id);
return ActionSupport.SUCCESS;
}
}
The remaining properties are expected to be ignored after doing this but it doesn't seem to work. Number of SQL statements associated with all of the entity classes are generated which in turn causes other severe errors to occur like,
org.apache.struts2.json.JSONException: java.lang.IllegalAccessException: Class
org.apache.struts2.json.JSONWriter can not access a member of class
org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone with modifiers "public"
What am I missing here? How to ignore all the properties except stateId and stateName?
I'm using Struts2-json-plugin-2.3.16.

You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"contentType", "text/javascript", "includeProperties",
"stateTables\\[\\d+\\]\\.stateId,stateTables\\[\\d+\\]\\.stateName"})

Related

JSON failed to lazily initialize a collection of roles

I am doing an exercise on the CRUD operations in a many-to-many relationship having attributes in the relationship table.
I am attaching my entities and I hope you can help me.
The error mentioned above occurs when I go to ask for the list of elements on the zetautente and zetamessaggio tables.
The same error occurs even when I go to ask for a single element of one of the two above mentioned tables ..
#Entity(name = "ZetaMessaggio")
#Table(name="zetamessaggio")
public class ZetaMessaggio implements Serializable {
private static final long serialVersionUID = -2387302703708194311L;
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "zetamessaggio_seq")
#SequenceGenerator(name = "zetamessaggio_seq",sequenceName = "zetamessaggio_seq",allocationSize = 1)
private Long id;
#Column(name = "titolo")
private String titolo;
#Column(name = "testo")
private String testo;
#OneToMany(
mappedBy = "zetaMessaggio",
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JsonManagedReference(value="zetaMessaggio")
private List<ZetaMessaggioUtente> zetaUtente = new ArrayList<ZetaMessaggioUtente>();
public ZetaMessaggio() {
}
public ZetaMessaggio(String titolo, String testo)
{
this.titolo = titolo;
this.testo = testo;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitolo() {
return titolo;
}
public void setTitolo(String titolo) {
this.titolo = titolo;
}
public String getTesto() {
return testo;
}
public void setTesto(String testo) {
this.testo = testo;
}
public List<ZetaMessaggioUtente> getZetaUtente() {
return zetaUtente;
}
public void setZetaUtente(List<ZetaMessaggioUtente> zetaUtenti) {
this.zetaUtente = zetaUtenti;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
ZetaMessaggio other = (ZetaMessaggio) o;
return Objects.equals(new Long(this.id), new Long(other.id))
&& Objects.equals(this.titolo, other.titolo)
&& Objects.equals(this.testo, other.testo);
}
#Override
public int hashCode() {
return Objects.hash( new Long(this.id)
, this.testo
, this.titolo
);
}
}
#Entity(name = "ZetaMessaggioUtente")
#Table(name = "zetamessaggioutente")
public class ZetaMessaggioUtente implements Serializable {
private static final long serialVersionUID = 4060038267093084727L;
#EmbeddedId
private ZetaMessaggioUtenteId id;
#Column(name="data")
private String data;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("idMessaggio")
#JoinColumn(name = "idMessaggio")
#JsonBackReference(value = "zetaMessaggio")
private ZetaMessaggio zetaMessaggio;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("idUtente")
#JoinColumn(name = "idUtente")
#JsonBackReference(value = "zetaUtente")
private ZetaUtente zetaUtente;
private ZetaMessaggioUtente() {}
public ZetaMessaggioUtente(ZetaMessaggioUtenteId id)
{
this.id = id;
}
public ZetaMessaggioUtente(ZetaMessaggio messaggio, ZetaUtente utente)
{
this.zetaMessaggio = messaggio;
this.zetaUtente = utente;
this.id = new ZetaMessaggioUtenteId(messaggio.getId(), utente.getId());
}
public ZetaMessaggioUtenteId getId() {
return id;
}
public void setId(ZetaMessaggioUtenteId id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public ZetaMessaggio getZetaMessaggio() {
return zetaMessaggio;
}
public void setZetaMessaggio(ZetaMessaggio zetaMessaggio) {
this.zetaMessaggio = zetaMessaggio;
}
public ZetaUtente getZetaUtente() {
return zetaUtente;
}
public void setZetaUtente(ZetaUtente zetaUtente) {
this.zetaUtente = zetaUtente;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
{
return false;
}
ZetaMessaggioUtente other = (ZetaMessaggioUtente) o;
return Objects.equals(zetaMessaggio, other.zetaMessaggio)
&& Objects.equals(zetaUtente, other.zetaUtente)
;
}
#Override
public int hashCode()
{
return Objects.hash(zetaMessaggio, zetaUtente);
}
}
#Embeddable
public class ZetaMessaggioUtenteId implements Serializable {
private static final long serialVersionUID = -7372159721389421199L;
#Column(name = "idMessaggio")
private Long idMessaggio;
#Column(name = "idUtente")
private Long idUtente;
private ZetaMessaggioUtenteId(){}
public ZetaMessaggioUtenteId(Long idMessaggio,Long idUtente){
setIdMessaggio(idMessaggio);
setIdUtente(idUtente);
}
public Long getIdMessaggio() {
return idMessaggio;
}
public void setIdMessaggio(Long idMessaggio) {
this.idMessaggio = idMessaggio;
}
public Long getIdUtente() {
return idUtente;
}
public void setIdUtente(Long idUtente) {
this.idUtente = idUtente;
}
#Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass())
{
return false;
}
ZetaMessaggioUtenteId other = (ZetaMessaggioUtenteId) o;
return Objects.equals(new Long(this.idMessaggio), new Long(other.idMessaggio)) &&
Objects.equals(new Long(this.idUtente), new Long(other.idUtente))
;
}
#Override
public int hashCode()
{
return Objects.hash( new Long(this.idMessaggio)
, new Long(this.idUtente)
);
}
}
#Entity(name = "ZetaUtenti")
#Table(name = "zetautenti",uniqueConstraints = {#UniqueConstraint(columnNames = {"Id"})})
public class ZetaUtente implements Serializable {
private static final long serialVersionUID = -5338956772143977741L;
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "zetautenti_seq")
#SequenceGenerator(name = "zetautenti_seq",sequenceName = "zetautenti_seq",allocationSize = 1)
private Long id;
#Column(name = "nome")
private String nome;
#Column(name = "cognome")
private String cognome;
#OneToMany(
mappedBy = "zetaUtente",
cascade = CascadeType.ALL,
orphanRemoval = true
)
#JsonManagedReference(value="zetaUtente")
private List<ZetaMessaggioUtente> zetaMessaggio = new ArrayList<ZetaMessaggioUtente>();
public ZetaUtente() {
}
public ZetaUtente(String nome, String cognome)
{
this.nome = nome;
this.cognome = cognome;
}
public Long getId() {
return id;
}
public void setId(Long id) {
id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public List<ZetaMessaggioUtente> getZetaMessaggio() {
return zetaMessaggio;
}
public void setZetaMessaggio(List<ZetaMessaggioUtente> zetaMessaggi) {
this.zetaMessaggio = zetaMessaggi;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
ZetaUtente other = (ZetaUtente) o;
return Objects.equals(new Long(this.id), new Long(other.id))
&& Objects.equals(this.nome, other.nome)
&& Objects.equals(this.cognome, other.cognome);
}
#Override
public int hashCode() {
return Objects.hash( new Long(this.id)
, this.nome
, this.cognome
);
}
}
By default #OneToMany and #ManyToMany relationships are lazy, so you need to handle receiving lazy data.
There are plenty of advices on the internet, it's very strange that you are asking this question, but if very quickly, you have few ways for getting lazy collection:
Antipatterns: OpenSessionInView and enable_lazy_load_no_trans
Most popular way: to use #Transactional annotation (auto attach object to session pool) or manual with start transaction, get collection, close transactional
Similar way: Hibernate.initialize(<get collection method>)
Manual way: use own SQL request with "JOIN FETCH ..."
Alternative way: to use #Fetch(FetchMode.SUBSELECT) (cannot say anything)
Not proper way (but the fastest temporary solution): to use FetchMode.EAGER for collection
Collections are lazily loaded by default, if you are not aware of this thing then you can check the link Lazy loading of collection.
To make your code working you need to add following in OneToMany :
fetch = FetchType.EAGER

inserting a foreign key in child table it showing null everytime

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.

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!!

Adding data to multiple tables using Spring forms in Spring MVC

I have the following database schema and I need to add data to all three tables using a single view http://i.stack.imgur.com/3HXhC.png (Due to stackoverflow rules, I cannot link the image directly).
What I hope to achieve, is to create an order, have it given an Workshop order id, and have it linked to LineItems which will let the user specify the quantity of items from the Inventory table to be added to the order.
I can create a workshop order in my database, and create a lineitem with the workshop orders id, and add the id and quantity from an inventory item into the lineitem table, and then use the attached code to display each lineitem orderline, with the total amount of items, which item is in the order, total price, customer name etc.
How do I go about creating a view that will let me create an order this way? The flow I imagine is:
Create workshop order -> add line items from inventory -> save the order.
Having worked on Spring and Hibernate for only a couple of weeks, I have not really figured out a smart approach to solve this, but hopefully someone in here has. By all means, feel free to criticize my database scheme, my classes and anything else. It may be a stupid design, not well suited for an actual production system.
I have attached my primary classes involved in this.
LineItems.java
#Entity
#Table(name = "LINE_ITEMS")
#AssociationOverrides({
#AssociationOverride(name = "pk.inventory",
joinColumns = #JoinColumn(name = "INVENTORY_Id")),
#AssociationOverride(name = "pk.workshop",
joinColumns = #JoinColumn(name = "WORKSHOP_ORDERS_Id"))
})
public class LineItems implements Serializable {
private static final long serialVersionUID = 5703588914404465647L;
#EmbeddedId
private LineItemsPK pk = new LineItemsPK();
private int quantity;
public LineItems() {
}
public LineItemsPK getPK() {
return pk;
}
public void setPK(LineItemsPK pk) {
this.pk = pk;
}
#Column(name = "WORKSHOP_ORDERS_Id", nullable=false, updatable=false,
insertable=false)
public Long getWorkshopOrdersId() {
return getPK().getWorkshop().getId();
}
#Column(name = "Id")
#JoinColumn(name="INVENTORY_Id", nullable=false, updatable=false, insertable=false)
public Long getInventoryId() {
return getPK().getInventory().getId();
}
#ManyToOne
public Workshop getWorkshop() {
return getPK().getWorkshop();
}
public void setWorkshop(Workshop workshop) {
getPK().setWorkshop(workshop);
}
#ManyToOne
#JoinColumn(name = "INVENTORY_Id")
public Inventory getInventory() {
return getPK().getInventory();
}
public void setInventory(Inventory inventory) {
getPK().setInventory(inventory);
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LineItems that = (LineItems) o;
if (getPK() != null ? !getPK().equals(that.getPK())
: that.getPK() != null) {
return false;
}
return true;
}
public int hashCode() {
return (getPK() != null ? getPK().hashCode() : 0);
}
}
LineItemsPK.java
#Embeddable
public class LineItemsPK implements Serializable {
private static final long serialVersionUID = -4285130025882317338L;
#ManyToOne
private Inventory inventory;
#ManyToOne
private Workshop workshop;
public Workshop getWorkshop() {
return workshop;
}
public void setWorkshop(Workshop workshop) {
this.workshop = workshop;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
#Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
LineItemsPK that = (LineItemsPK) o;
if(workshop != null ? !workshop.equals(that.workshop) : that.workshop != null) {
return false;
}
if(inventory != null ? !inventory.equals(that.inventory) : that.inventory != null) {
return false;
}
return true;
}
#Override
public int hashCode() {
int result;
result = (workshop != null ? workshop.hashCode() : 0);
result = 31 * result + (inventory != null ? inventory.hashCode() : 0);
return result;
}
}
Workshop.java
#Entity
#Table(name = "WORKSHOP_ORDERS")
public class Workshop implements Serializable {
private static final long serialVersionUID = -8106245965993313684L;
public Long id;
public Long inventoryItemId;
public String workshopService;
public String workshopNotes;
public Long customersId;
public Long paymentId;
private Customer customer;
private Payment payment;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Workshop() {
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
}
public Workshop(Long inventoryItemId, String workshopService, String workshopNotes,
Customer customer, Payment payment, Set<LineItems> lineItems) {
this.inventoryItemId = inventoryItemId;
this.workshopService = workshopService;
this.workshopNotes = workshopNotes;
this.customer = customer;
this.payment = payment;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.workshop", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#ManyToOne
#JoinColumn(name="CUSTOMERS_Id", nullable = false, insertable = false, updatable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(final Customer customer) {
this.customer = customer;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="PAYMENT_Id", insertable = false, updatable = false, nullable = false)
public Payment getPayment() {
return payment;
}
public void setPayment(final Payment payment) {
this.payment = payment;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", nullable = false)
public Long getId() {
return id;
}
#Column(name = "InventoryItemId")
public Long getInventoryItemId() {
return inventoryItemId;
}
#Column(name = "WorkshopService")
public String getWorkshopService() {
return workshopService;
}
#Column(name = "WorkshopNotes")
public String getWorkshopNotes() {
return workshopNotes;
}
#Column(name = "CUSTOMERS_Id")
public Long getCustomersId() {
return customersId;
}
#Column(name = "PAYMENT_Id")
public Long getPaymentId() {
return paymentId;
}
public void setId(Long id) {
this.id = id;
}
public void setInventoryItemId(Long inventoryItemId) {
this.inventoryItemId = inventoryItemId;
}
public void setWorkshopService(String workshopService) {
this.workshopService = workshopService;
}
public void setWorkshopNotes(String workshopNotes) {
this.workshopNotes = workshopNotes;
}
public void setCustomersId(Long customersId) {
this.customersId = customersId;
}
public void setPaymentId(Long paymentId) {
this.paymentId = paymentId;
}
public String toString() {
return "Customer id: " + this.customersId + "Notes: " + workshopNotes;
}
}
Inventory.java
#Entity
#Table(name = "INVENTORY")
public class Inventory implements Serializable {
private static final long serialVersionUID = -8907719450013387551L;
private Long id;
private String itemName;
private String itemVendorName;
private Long itemInventoryStatus;
private Double itemBuyPrice;
private Double itemSellPrice;
private Set<LineItems> lineItems = new HashSet<LineItems>(0);
public Inventory() {
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
}
public Inventory(String itemName, String itemVendorName, Long itemInventoryStatus,
Double itemBuyPrice, Double itemSellPrice, Set<LineItems> lineItems) {
this.itemName = itemName;
this.itemVendorName = itemVendorName;
this.itemInventoryStatus = itemInventoryStatus;
this.itemBuyPrice = itemBuyPrice;
this.itemSellPrice = itemSellPrice;
this.lineItems = lineItems;
}
#OneToMany(mappedBy = "pk.inventory", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LineItems> getLineItems() {
return this.lineItems;
}
public void setLineItems(Set<LineItems> lineItems) {
this.lineItems = lineItems;
}
#Id
#Column(name = "Id", nullable = false)
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return this.id;
}
#Column(name = "ItemName")
public String getItemName() {
return this.itemName;
}
#Column(name = "ItemVendorName")
public String getItemVendorName() {
return this.itemVendorName;
}
#Column(name = "ItemInventoryStatus")
public Long getItemInventoryStatus() {
return this.itemInventoryStatus;
}
#Column(name = "ItemBuyPrice")
public Double getItemBuyPrice() {
return this.itemBuyPrice;
}
#Column(name = "ItemSellPrice")
public Double getItemSellPrice() {
return this.itemSellPrice;
}
public void setId(Long id) {
this.id = id;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public void setItemVendorName(String itemVendorName) {
this.itemVendorName = itemVendorName;
}
public void setItemInventoryStatus(Long itemInventoryStatus) {
this.itemInventoryStatus = itemInventoryStatus;
}
public void setItemBuyPrice(Double itemBuyPrice) {
this.itemBuyPrice = itemBuyPrice;
}
public void setItemSellPrice(Double itemSellPrice) {
this.itemSellPrice = itemSellPrice;
}
public String toString() {
return "Item id:" + this.id + " ItemName: " + this.itemName +
" ItemInventoryStatus: " + this.itemInventoryStatus +
" ItemBuyPrice: " + this.itemBuyPrice + " ItemSellPrice " + this.itemSellPrice;
}
}
This isn't really a question as it is more of a "how would I do this"
What have you tried already?
Where are you running into trouble?
etc.
Your view logic should not be coupled with your domain layer, what I mean is, you write your forms to be as usable as possible yet, still get the information you need. Once you post the information to the backing Controller, you do the required business logic in order to line up how the entities persist, etc.
Continuing this line of thinking, your controller should only be worried about web layer exceptions, and passing information on to the Business / Service Layer. From the Business / Service layer you execute required logic, and pass on to the Domain / Repository layer. This gives a clear separation of concerns allowing for easier testing.