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;
}
Related
I am having an unusual error, when doing a get in postman, my method returns some values called target and targetClass, I don't know why, since I am implementing an interface just to bring some specific values, if you could help would be very appreciated
This is the model
#Entity
#Table(name = "tudb_users")
public class Tudb_users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int userId;
#Column(name = "client_id")
private Integer clientId;
#Column(name = "name")
private String name;
#Column(name = "last_name")
private String lastName;
#Column(name = "rol_id")
private Integer rolId;
#Column(name = "clinic_id")
private Integer clinicId;
#Column(name = "password")
private String password;
#Column(name = "rfc")
private String rfc;
#Column(name = "gender")
private Integer gender;
#Column(name = "date_born")
private String dateBorn;
#Column(name = "email")
private String email;
#Column(name = "phone")
private String phone;
#Column(name = "identification_card")
private String identificationCard;
#Column(name = "photo")
private String photo;
#Column(name = "folder")
private String folder;
#Column(name = "session")
private Integer session;
#Column(name = "promotion_code")
private String promotionCode;
#Column(name = "last_session")
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yy-MM-dd' 'HH:mm")
private Date lastSession;
#Column(name = "token")
private String token;
#Column(name = "token_email")
private String tokenEmail;
#Column(name = "status")
private Integer status;
#Column(name = "user_register")
private Integer userRegister;
#Column(name = "date_register")
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yy-MM-dd' 'HH:mm")
private Date dateRegister;
#Column(name = "user_update")
private Integer userUpdate;
#Column(name = "date_update")
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yy-MM-dd' 'HH:mm")
private Date dateUpdate;
#Column(name = "options")
private Integer options;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Integer getClientId() {
return clientId;
}
public void setClientId(Integer clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getRolId() {
return rolId;
}
public void setRolId(Integer rolId) {
this.rolId = rolId;
}
public Integer getClinicId() {
return clinicId;
}
public void setClinicId(Integer clinicId) {
this.clinicId = clinicId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRfc() {
return rfc;
}
public void setRfc(String rfc) {
this.rfc = rfc;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getDateBorn() {
return dateBorn;
}
public void setDateBorn(String dateBorn) {
this.dateBorn = dateBorn;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getIdentificationCard() {
return identificationCard;
}
public void setIdentificationCard(String identificationCard) {
this.identificationCard = identificationCard;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getFolder() {
return folder;
}
public void setFolder(String folder) {
this.folder = folder;
}
public Integer getSession() {
return session;
}
public void setSession(Integer session) {
this.session = session;
}
public Date getLastSession() {
return lastSession;
}
public void setLastSession(Date lastSession) {
this.lastSession = lastSession;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getUserRegister() {
return userRegister;
}
public void setUserRegister(Integer userRegister) {
this.userRegister = userRegister;
}
public Date getDateRegister() {
return dateRegister;
}
public void setDateRegister(Date dateRegister) {
this.dateRegister = dateRegister;
}
public Integer getUserUpdate() {
return userUpdate;
}
public void setUserUpdate(Integer userUpdate) {
this.userUpdate = userUpdate;
}
public Date getDateUpdate() {
return dateUpdate;
}
public void setDateUpdate(Date dateUpdate) {
this.dateUpdate = dateUpdate;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getTokenEmail() {
return tokenEmail;
}
public void setTokenEmail(String tokenEmail) {
this.tokenEmail = tokenEmail;
}
public Integer getOptions() {
return options;
}
public void setOptions(Integer options) {
this.options = options;
}
public String getPromotionCode() {
return promotionCode;
}
public void setPromotionCode(String promotionCode) {
this.promotionCode = promotionCode;
}
}
Now this is repository
#Repository
public interface TudbUsersRepository extends JpaRepository<Tudb_users, Long>{
#Query(value = "SELECT tudb_users.user_id, tudb_users.client_id, tu_clients.name as nameCliente, tudb_users.clinic_id, tudb_users.rol_id, tudb_roles.description as rolName, tudb_users.name, tudb_users.last_name,\r\n"
+ "tudb_users.email, tudb_users.photo, tudb_users.rfc, tudb_users.gender, tudb_users.date_born, tudb_users.folder, tudb_users.token\r\n"
+ "FROM dentabash_dev.tudb_users inner join tu_clients on tu_clients.client_id = tudb_users.client_id\r\n"
+ "inner join tudb_roles on tudb_roles.rol_id = tudb_users.rol_id where tudb_users.client_id = ?1", nativeQuery = true)
List<DentaUser> getUsersByClientId(Integer id);
}
This is the interface
public interface DentaUser {
Integer getUser_id();
Integer getClient_id();
Integer getClinic_id();
Integer getRol_id();
String getNameCliente();
String getRolName();
String getName();
String getLast_name();
String getEmail();
String getPhoto();
String getRfc();
Integer getGender();
#Temporal(TemporalType.TIMESTAMP)
#JsonFormat(pattern = "yy-MM-dd' 'HH:mm")
Date getDate_born();
String getFolder();
String getToken();
}
This is the service
#Service
public class TudbUsersServices {
#Autowired
private TudbUsersRepository repo;
public ResponseEntity<?> getUserByClientID(Integer id){
JSONObject response = new JSONObject();
try {
response.put("code", 200);
response.put("success", true);
response.put("data", repo.getUsersByClientId(id));
return new ResponseEntity<>(response.toString(), HttpStatus.OK);
}catch(Exception e) {
response.put("code", 400);
response.put("success", false);
response.put("message", "Bad request" + e.getMessage());
return new ResponseEntity<>(response.toString(), HttpStatus.OK);
}
}
}
And this is controller:
#RestController
#RequestMapping("/dbusers")
#Tag(name = "DentaBash Users", description = "DentaBash Users - Controller")
#CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class TudbUsersController {
#Autowired
private TudbUsersServices service;
#RequestMapping(value = "/usersByClient", method = RequestMethod.GET)
public ResponseEntity<?> getUserByClientID(#RequestParam Integer clientId){
return service.getUserByClientID(clientId);
}
}
Now I get this in postman:
{
"code": 200,
"data": [
{
"gender": 0,
"photo": "images/user.png",
"last_name": "Ortiz",
"client_id": 2,
"rfc": "TESTRFC",
"target": {
"gender": 0,
"last_name": "Ortiz",
"photo": "images/user.png",
"client_id": 2,
"rfc": "TESTRFC",
"token": "5mi7oit016l768aaj1mecgmgu6",
"folder": "images/test/folder",
"user_id": 4,
"date_born": "2022-02-01",
"name": "Juan",
"nameCliente": "Jose Luis Miranda Pavon",
"rol_id": 4,
"rolName": "Cirujano Dentista - Gerente",
"clinic_id": 1,
"email": "juan#gmail.com"
},
"token": "5mi7oit016l768aaj1mecgmgu6",
"folder": "images/test/folder",
"user_id": 4,
"targetClass": "class org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap",
"name": "Juan",
"nameCliente": "Jose Luis Miranda Pavon",
"rol_id": 4,
"rolName": "Cirujano Dentista - Gerente",
"clinic_id": 1,
"email": "juan#gmail.com"
}
],
"success": true
}
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.
So I am building a REST api using SpringDataRest both Get and Post are working but I don´t know whats wrong with the PUT.
This is the entity im using:
#Entity
#Table(name = "companies")
public class Company {
#Id
#Column(name="CompanyId", nullable=false, unique=true)
private String companyId;
#Column(name="Name", nullable=false)
private String name;
#Column(name="ContactName", nullable=false)
private String contactName;
#Column(name="ContactSurName")
private String contactSurname;
#Column(name="ContactEmail", nullable=false)
private String contactEmail;
#Column(name="ContactPhone")
private String contactPhone;
#Column(name="Enabled", nullable=false)
private String enabled;
#Column(name="Logo")
private String logo;
#Column(name = "CreationDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
#Column(name = "LastUpdateDate", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateDate;
//Region Constructors
private Company(){}
public Company(String companyId, String name, String contactName, String contactSurname, String contactEmail, String contactPhone,
String enabled){
this.companyId = companyId;
this.name = name;
this.contactName = contactName;
this.contactSurname = contactSurname;
this.contactEmail = contactEmail;
this.contactPhone = contactPhone;
this.enabled = enabled;
this.creationDate = new Date();
this.lastUpdateDate = new Date();
}
//EndRegion
//Region Getters & Setters
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactSurname() {
return contactSurname;
}
public void setContactSurname(String contactSurname) {
this.contactSurname = contactSurname;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getEnabled() {
return enabled;
}
public void setEnabled(String enabled) {
this.enabled = enabled;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastUpdateDate() {
return lastUpdateDate;
}
public void setLastUpdateDate(Date lastUpdateDate) {
this.lastUpdateDate = lastUpdateDate;
}
//EndRegion
}
When I execute this request:
REQUEST
I get this response:
{
"cause": {
"cause": null,
"message": "No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
},
"message": "Could not read an object of type class com.wipma.application.domain.Company from the request!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input\n at [Source: org.apache.catalina.connector.CoyoteInputStream#1130374; line: 1, column: 0]"
}
I can´t figure out whats wrong, I suspect its something related with some field mapping but cant sort it out.
Thanks in advance
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!!
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"})