#RequestBody variable returning null properties [duplicate] - java

This question already has answers here:
#RequestBody is getting null values
(17 answers)
Closed 3 years ago.
I wrote a controller for receiving a post request that posts json however when i try to access the object fields it returns null. The code for the Controller is below
package com.example;
import com.example.Services.ZesaServices;
import com.example.models.Zesa.ZesaRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MoneyResource {
#RequestMapping("/services")
public String getServices(){
return "We do everything";
}
#PostMapping(value="/zesa")
public String payZesa(#RequestBody ZesaRequest newZesaRequest){
Logger log = LoggerFactory.getLogger(YomoneyResource.class);
log.info("Json Object parsed works eg: "+newZesaRequest.getMeterNumber());
return newZesaRequest.getMeterNumber().toString();
}
}
And the ZesaRequest Object is as follows
package com.example.models.Zesa;
public class ZesaRequest {
private Double Amount;
private String MeterNumber;
private String PaymentAccountNumber;
private String PaymentAccountDetails;
private int PaymentMethod;
private String MobileNumber;
private String AgentAccountDetails;
private int TransactionType;
public ZesaRequest() {
}
public ZesaRequest(Double amount, String meterNumber, String paymentAccountNumber, String paymentAccountDetails,
int paymentMethod, String mobileNumber, String agentAccountDetails, int transactionType) {
this.Amount = amount;
this.MeterNumber = meterNumber;
this.PaymentAccountNumber = paymentAccountNumber;
this.PaymentAccountDetails = paymentAccountDetails;
this.PaymentMethod = paymentMethod;
this.MobileNumber = mobileNumber;
this.AgentAccountDetails = agentAccountDetails;
this.TransactionType = transactionType;
}
public String getPaymentAccountDetails() {
return PaymentAccountDetails;
}
public void setPaymentAccountDetails(String paymentAccountDetails) {
PaymentAccountDetails = paymentAccountDetails;
}
public String getMobileNumber() {
return MobileNumber;
}
public void setMobileNumber(String mobileNumber) {
MobileNumber = mobileNumber;
}
public Double getAmount() {
return Amount;
}
public void setAmount(Double amount) {
Amount = amount;
}
public String getMeterNumber() {
return MeterNumber;
}
public void setMeterNumber(String meterNumber) {
MeterNumber = meterNumber;
}
public String getPaymentAccountNumber() {
return PaymentAccountNumber;
}
public void setPaymentAccountNumber(String paymentAccountNumber) {
PaymentAccountNumber = paymentAccountNumber;
}
public int getPaymentMethod() {
return PaymentMethod;
}
public void setPaymentMethod(int paymentMethod) {
PaymentMethod = paymentMethod;
}
public String getAgentAccountDetails() {
return AgentAccountDetails;
}
public void setAgentAccountDetails(String agentAccountDetails) {
AgentAccountDetails = agentAccountDetails;
}
public int getTransactionType() {
return TransactionType;
}
public void setTransactionType(int transactionType) {
TransactionType = transactionType;
}
}
My code is printing null When I send the request below
{
"AgentAccountDetails":"example:123",
"MeterNumber":"1110-52-8867",
"PaymentMethod":1,
"Amount":10.50,
"MobileNumber":"0123456789",
"TransactionType":1,
"PaymentAccountNumber":"0123456789",
"PaymentAccountDetails":"null"
}
When I run it it returns an empty String. I am not sure where the problem is I have looked into other examples and they followed a similar pattern and I ran their code and it worked as expected but mine seems to not be converting the json body into the Java object.

You can solve this by using the #JsonProperty annotation above the fields like this:
...
#JsonPropety(value = "Amount")
private Double amount;
...
Or you can rename your properties to start with lowercase letter (both in the VM and in the incoming json), as #OrangeDog suggested in the comments.

Your class defines a property called meterNumber, but your JSON object says MeterNumber instead.
If you must have MeterNumber in your JSON you will need to add #JsonProperty annotations.
It is against both Java and JSON naming conventions to start field names with a capital letter.
As an aside, you can avoid all the boilerplate by using Lombok:
#Data
public class ZesaRequest {
#JsonProperty("Amount")
private Double amount;
#JsonProperty("MeterNumber")
private String meterNumber;
#JsonProperty("PaymentAccountNumber")
private String paymentAccountNumber;
#JsonProperty("PaymentAccountDetails")
private String paymentAccountDetails;
#JsonProperty("PaymentMethod")
private int paymentMethod;
#JsonProperty("MobileNumber")
private String mobileNumber;
#JsonProperty("AgentAccountDetails")
private String agentAccountDetails;
#JsonProperty("TransactionType")
private int transactionType;
}
You also probably don't want "PaymentAccountDetails":"null". It should be either "PaymentAccountDetails":null, or omitted entirely.

Related

How can I indicate the PathVariable for Spring REST-method?

I want to indicate the pathvariable secondpart. Thats not possible because an errormessage shows: Could not determine type for: veranstaltung.Identificationnumber, at table: teilnehmer, for columns: [org.hibernate.mapping.Column(id)]
What I have to change to use the variable secondpart? How can I access the variable secondpart in the method of the Controller?
package veranstaltung;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Teilnehmer {
static int idnumber=69;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Identificationnumber id;
private String name;
private String vorname;
private String wohnort;
protected Teilnehmer() {}
public Teilnehmer(Identificationnumber id, String name, String vorname,String wohnort)
{
this.id=id;
this.name=name;
this.vorname=vorname;
this.wohnort=wohnort;
}
public static String erzeugeID ()
{
String id= "JAVALAND-";
id=id+idnumber;
idnumber++;
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getWohnort() {
return wohnort;
}
public void setWohnort(String wohnort) {
this.wohnort = wohnort;
}
#Override
public String toString()
{
return id.getfullID()+" "+getName()+" "+getVorname()+" "+getWohnort();
}
}
package veranstaltung;
public class Identificationnumber {
private String firstpart;
private Long secondpart;
public Identificationnumber(String firstpart, Long secondpart)
{
this.firstpart=firstpart;
this.secondpart=secondpart;
}
public String getFirstpart() {
return firstpart;
}
public void setFirstpart(String firstpart) {
this.firstpart = firstpart;
}
public Long getSecondpart() {
return secondpart;
}
public void setSecondpart(Long secondpart) {
this.secondpart = secondpart;
}
public String getfullID()
{
return firstpart+' '+secondpart;
}
}
package veranstaltung;
import veranstaltung.Teilnehmer;
import veranstaltung.Identificationnumber;
import veranstaltung.TeilnehmerRepository;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
public class TeilnehmerController {
#Autowired
TeilnehmerRepository teilnehmerRepository;
#GetMapping("/teilnehmer")
Iterable<Teilnehmer> teilnehmer(){
return this.teilnehmerRepository.findAll();
}
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(secondpart);
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
}
}
Your Identificationnumber is not primitive but custom class. What you are doing is trying to use Long against your Identificationnumber in teilnehmerById method.
I would suggest to either change #Id column of Teilnehmer to Long from Identificationnumber or you can still pass Identificationnumber in teilnehmerById method by doing something like below (This is based on consideration that you have implemented your own findById which will convert Identificationnumber to Long):
#GetMapping("/teilnehmer/{id}")
Teilnehmer teilnehmerById(#PathVariable Long secondpart){
Identificationnumber number = new Identificationnumber();
number.setSecondpart(secondpart);
Optional<Teilnehmer> teilnehmerOptional = this.teilnehmerRepository.findById(number.getfullID());
if(teilnehmerOptional.isPresent()) {
return teilnehmerOptional.get();
}
return null;
Based on hibernate error, it looks like you have to use my first option which is change #Id of Teilnehmer to Long.
Edit : just updated code so that you can use composition of String to Long.

DynamoDB/Jackson removing 'is' prefix from property name of the entity [duplicate]

I have a dynamodb table named opx_user_profiles. The entity is shown below, however the attribute user_profile_id is getting saved as userProfileID in the table, even though the #DynamoDBAttribute(attributeName = USER_PROFILE_ID) is specified on the attribute. Other attributes like date_created are getting saved as expected.
I have read the documentation but still not able to find the root cause of the issue. Is it is a bug in dynamo DB?
#DynamoDBTable(tableName = "opx_user_profiles")
public class UserProfileEntity implements Serializable
{
public static final String USER_PROFILE_ID="user_profile_id";
public static final String DATE_CREATED = "date_created";
public static final String EXPIRY_DATE = "expiry_date";
public static final String USERNAME ="username";
public static final String CONTACT_NAME ="contact_name";
private static final long serialVersionUID = 1L;
#DynamoDBAttribute(attributeName = USER_PROFILE_ID)
private Integer userProfileId;
#DynamoDBAttribute(attributeName = USERNAME)
private String userName;
#DynamoDBAttribute(attributeName = CONTACT_NAME)
private String contactName;
#DynamoDBAttribute(attributeName = DATE_CREATED)
private Date dateCreated;
#DynamoDBAttribute(attributeName = EXPIRY_DATE)
private long expiryDate;
public Integer getUserProfileID()
{
return userProfileId;
}
public void setUserProfileID(Integer userProfileId)
{
this.userProfileId = userProfileId;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getContactName()
{
return contactName;
}
public void setContactName(String contactName)
{
this.contactName = contactName;
}
public Date getDateCreated()
{
return dateCreated;
}
public void setDateCreated(Date dateCreated)
{
this.dateCreated = dateCreated;
}
}
Even though the official AWS documentation says we may apply the annotation #DynamoDBAttribute class field, I could not make it work like this. However, as seen in this AWS example, I could apply without any problem the annotation to the getter methods.
Please try the following:
#DynamoDBTable(tableName = "opx_user_profiles")
public class UserProfileEntity implements Serializable
{
public static final String USER_PROFILE_ID="user_profile_id";
...
private Integer userProfileId;
...
#DynamoDBAttribute(attributeName = USER_PROFILE_ID)
public Integer getUserProfileID()
{
return userProfileId;
}
public void setUserProfileID(Integer userProfileId)
{
this.userProfileId = userProfileId;
}
...
}
One more option.
If you want to reduce code boilerplates you might use Lombok's #Getter this way:
#Getter(onMethod = #__({#DynamoDbAttribute("address")}))
private String address;
p.s.: It won't impact performance cause the code generation happens not in runtime but the entity looks better IMO.

How to add array list to rest API request using Rest Assured?

I'm using rest assured for Rest api testing with the help of POJO classes like getter and setter methods to set the values but i'm stuck with array list in between rest request,please any one provide proper code to get exact below request to post using rest assured.
Request:
{
"firstName":"SuryaNAMASKARAM",
"lastName":"mangalam",
"mobileNo" :4954758490,
"emailId" :"surya.mangalam#futureretail.in",
"houseNoStreet":"123456",
"buildingName":"",
"landmark":"Nirmala jathara",
"paymentDetail" :
[{"paymentType":"CASH","No":"3519000012","Date":"16-06-2018","amount":"100.00"}]
}
CustomerCreate Class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("firstName")
#Expose
private String firstName;
#SerializedName("lastName")
#Expose
private String lastName;
#SerializedName("mobileNo")
#Expose
private Integer mobileNo;
#SerializedName("emailId")
#Expose
private String emailId;
#SerializedName("houseNoStreet")
#Expose
private String houseNoStreet;
#SerializedName("buildingName")
#Expose
private String buildingName;
#SerializedName("landmark")
#Expose
private String landmark;
#SerializedName("paymentDetail")
#Expose
private List<PaymentDetail> paymentDetail = null;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMobileNo() {
return mobileNo;
}
public void setMobileNo(Integer mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getHouseNoStreet() {
return houseNoStreet;
}
public void setHouseNoStreet(String houseNoStreet) {
this.houseNoStreet = houseNoStreet;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public List<PaymentDetail> getPaymentDetail() {
return paymentDetail;
}
public void setPaymentDetail(List<PaymentDetail> paymentDetail) {
this.paymentDetail = paymentDetail;
}
}
PaymentDetails:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PaymentDetail {
#SerializedName("paymentType")
#Expose
private String paymentType;
#SerializedName("No")
#Expose
private String no;
#SerializedName("Date")
#Expose
private String date;
#SerializedName("amount")
#Expose
private String amount;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Test Class:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.requestpojo.Example;
import com.test.requestpojo.PaymentDetail;
public class TestAPI {
public void setTestData() throws JSONException {
Example example = new Example();
example.setFirstName("Rajesh");
example.setLastName("Kuchana");
example.setMobileNo("3434343434");
example.setEmailId("rajesh.kuchana#futureretail.in");
example.setDateOfBirth("10-10-2018");
example.setGender(1);
example.setHouseNoStreet("Test");
example.setBuildingName("Test");
example.setLandmark("Test");
List<PaymentDetail> data = new ArrayList<PaymentDetail>();
PaymentDetail paymentDetail = new PaymentDetail();
paymentDetail.setAmount("999.00");
data.add(paymentDetail);
JSONObject jsonObject = new JSONObject(example);
JSONArray jsonArray = new JSONArray(data);
jsonArray.put(data);
System.out.println(jsonArray.put(data));
}
In your test class, what you must do is separate the test data creation to a different class and pass that as data provider to your test method. This is from design point of view.
Coming to your problem:
You are already using gson, why are you constructing a JSONObject. Instead do something like below;
Gson gson = new Gson();
String _my_obj = gson.toJson(example);
Hope this is what you are looking for.

Access JSON value called "class" with Gson

I am trying to get the value of class in the following JSON:
{
"battlegroup": "Misery",
"class": 1,
"race": 4,
"gender": 0
}
I access the other fields (battlegroup, race etc.) with:
WoWDetails info = gson.fromJson(response, WoWDetails.class);
raceID = info.race;
WoWDetails is as following:
class WoWDetails {
// character details
public String battlegroup;
public Integer achievementPoints;
public Integer race;
public Integer class;
}
But if I try WoWDetails.class it's giving me an error saying "Unknown class: info". Which makes sense because info is not a class.
Is there a way around this? Can I escape the word "class" in any way possible?
The name class is not editable, since it's not my API.
You can map the class field to JSON key using #SerializedName
WowDetails.java
public class WoWDetails {
String battlegroup;
#SerializedName("class")
int className;
int race;
int gender;
}
Set your Package name
package com.nonprofit.nonprofit;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WoWDetails {
#SerializedName("battlegroup")
#Expose
private String battlegroup;
#SerializedName("class")
#Expose
private Integer _class;
#SerializedName("race")
#Expose
private Integer race;
#SerializedName("gender")
#Expose
private Integer gender;
public String getBattlegroup() {
return battlegroup;
}
public void setBattlegroup(String battlegroup) {
this.battlegroup = battlegroup;
}
public Integer getClass_() {
return _class;
}
public void setClass_(Integer _class) {
this._class = _class;
}
public Integer getRace() {
return race;
}
public void setRace(Integer race) {
this.race = race;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
}
You can get your details like below
WoWDetails info = gson.fromJson(response, WoWDetails.class);
info.getGender();
info.getRace();

Empty join table for ManyToMany Relationship

A similar question with a different issue has been answered before. I have a bidirectional #ManyToMany relationship using Hibernate. The data persists to the separate entity tables, but the id column that maps to the entity tables is empty. I have tried the suggestions in Empty Join Table resulting from JPA ManyToMany, ManyToMany relationship, deleting records from relationship table and Hibernate Many-to-many association: left hand side collection contains elements, but right hand side collection is empty, but have not had success so far. Below is my code for completeness (I am still learning java and the spring framework, so I apologise for any rookie mistakes in advance):
CaseStudy Class
#Entity
public class CaseStudy {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Long caseStudyId;
private String location;
private String equipment;
private String issue;
private String solution;
private String benefit;
private float upper_dissolved_Oxygen;
private float lower_dissolved_Oxygen;
private float upper_pH;
private float lower_pH;
private float upper_temp;
private float lower_temp;
private float upper_conductivity;
private float lower_conductivity;
#CreationTimestamp
private Date created;
#ManyToOne
#JsonBackReference
private User user;
private int likes;
#ManyToMany(mappedBy="casestudyList", fetch = FetchType.EAGER)
private List<WaterQuality> waterQualityList = new List<WaterQuality>();
#OneToMany(mappedBy = "casestudy", fetch = FetchType.EAGER)
private List<Comment> commentList;
public Long getCaseStudyId() {
return caseStudyId;
}
public void setCaseStudyId(Long caseStudyId) {
this.caseStudyId = caseStudyId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
public String getBenefit() {
return benefit;
}
public void setBenefit(String benefit) {
this.benefit = benefit;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
public String getEquipment() {
return equipment;
}
public void setEquipment(String equipment) {
this.equipment = equipment;
}
public float getUpper_dissolved_Oxygen() {
return upper_dissolved_Oxygen;
}
public void setUpper_dissolved_Oxygen(float upper_dissolved_Oxygen) {
this.upper_dissolved_Oxygen = upper_dissolved_Oxygen;
}
public float getLower_dissolved_Oxygen() {
return lower_dissolved_Oxygen;
}
public void setLower_dissolved_Oxygen(float lower_dissolved_Oxygen) {
this.lower_dissolved_Oxygen = lower_dissolved_Oxygen;
}
public float getUpper_pH() {
return upper_pH;
}
public void setUpper_pH(float upper_pH) {
this.upper_pH = upper_pH;
}
public float getLower_pH() {
return lower_pH;
}
public void setLower_pH(float lower_pH) {
this.lower_pH = lower_pH;
}
public float getUpper_temp() {
return upper_temp;
}
public void setUpper_temp(float upper_temp) {
this.upper_temp = upper_temp;
}
public float getLower_temp() {
return lower_temp;
}
public void setLower_temp(float lower_temp) {
this.lower_temp = lower_temp;
}
public float getUpper_conductivity() {
return upper_conductivity;
}
public void setUpper_conductivity(float upper_conductivity) {
this.upper_conductivity = upper_conductivity;
}
public float getLower_conductivity() {
return lower_conductivity;
}
public void setLower_conductivity(float lower_conductivity) {
this.lower_conductivity = lower_conductivity;
}
public List<WaterQuality> getWaterQualityList() {
return waterQualityList;
}
public void setWaterQualityList(List<WaterQuality> waterQualityList) {
this.waterQualityList = waterQualityList;
}
}
WaterQuality Class
#Entity
public class WaterQuality {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long waterQualityId;
private String description;
private String status;
private float dissolved_Oxygen;
private float pH;
private float temp;
private float conductivity;
#CreationTimestamp
private Date publishDate;
#ManyToOne
#JsonBackReference
private User user;
#ManyToMany(targetEntity = CaseStudy.class, cascade = {CascadeType.ALL})
#JoinTable(
joinColumns = {#JoinColumn(name="water_quality_id")},
inverseJoinColumns = {#JoinColumn(name="case_study_id")})
private Set<CaseStudy> casestudyList = new HashSet<CaseStudy>();
public Long getWaterQualityId() {
return waterQualityId;
}
public void setWaterQualityId(Long waterQualityId) {
this.waterQualityId = waterQualityId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public float getDissolved_Oxygen() {
return dissolved_Oxygen;
}
public void setDissolved_Oxygen(float dissolved_Oxygen) {
this.dissolved_Oxygen = dissolved_Oxygen;
}
public float getpH() {
return pH;
}
public void setpH(float pH) {
this.pH = pH;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getConductivity() {
return conductivity;
}
public void setConductivity(float conductivity) {
this.conductivity = conductivity;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<CaseStudy> getCasestudyList() {
return casestudyList;
}
public void setCasestudyList(Set<CaseStudy> casestudyList) {
this.casestudyList = casestudyList;
}
public List<CaseStudy> getDissolvedOxygenalert() {
List<CaseStudy> dissolvedOxygenalert = casestudyList.stream() //convert list to stream
.filter(casestudy -> casestudy.getUpper_dissolved_Oxygen() < getDissolved_Oxygen() || casestudy.getLower_dissolved_Oxygen() > getDissolved_Oxygen())
.collect(Collectors.toList()); //collect the output and convert streams to a List
System.out.print(dissolvedOxygenalert);
return dissolvedOxygenalert;
}
}
I have tried deleting the database and creating it again, but it hasn't solved the problem so far.
Below is the code for persisting the data to the database
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CaseStudy Service Implementation
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scrunch.data.dao.CaseStudyDao;
import com.scrunch.data.model.CaseStudy;
import com.scrunch.data.model.User;
import com.scrunch.data.service.CaseStudyService;
#Service
public class CaseStudyServiceImpl implements CaseStudyService{
#Autowired
private CaseStudyDao casestudyDao;
public CaseStudy save(CaseStudy casestudy) {
return casestudyDao.save(casestudy);
}
public Set<CaseStudy> findByUser(User user) {
return casestudyDao.findByUser(user);
}
public CaseStudy findByCaseStudyId(Long caseStudyId) {
return casestudyDao.findByCaseStudyId(caseStudyId);
}
public Set<CaseStudy> findAll() {
return casestudyDao.findAll();
}
}
WaterQuality Service Implementation
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scrunch.data.dao.WaterQualityDao;
import com.scrunch.data.model.User;
import com.scrunch.data.model.WaterQuality;
import com.scrunch.data.service.WaterQualityService;
#Service
public class WaterQualityServiceImpl implements WaterQualityService{
// private static final Logger LOGGER = LoggerFactory.getLogger(WaterQualityServiceImpl.class);
#Autowired
private WaterQualityDao waterQualityDao;
#Override
public List<WaterQuality> listAllWaterQualityByUserAndDescription(
User user, String description) {
return waterQualityDao.findAllWaterQualityByUserAndDescriptionContaining(user, description);
}
#Override
public WaterQuality save(WaterQuality waterQuality) {
return waterQualityDao.save(waterQuality);
}
#Override
public List<WaterQuality> findByUser(User user) {
return waterQualityDao.findByUser(user);
}
#Override
public WaterQuality findWaterQualityById(Long waterQualityId) {
return waterQualityDao.findByWaterQualityId(waterQualityId);
}
#Override
public List<WaterQuality> findAll() {
return waterQualityDao.findAll();
}
}
WaterQuality Controller
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.scrunch.data.model.CaseStudy;
import com.scrunch.data.model.User;
import com.scrunch.data.model.WaterQuality;
import com.scrunch.data.service.WaterQualityService;
#RestController
#RequestMapping("/rest")
public class WaterQualityResource {
private String location;
private String equipment;
private String issue;
private String solution;
private String benefit;
private float upper_dissolved_Oxygen;
private float lower_dissolved_Oxygen;
private int likes;
#Autowired
private WaterQualityService waterQualityService;
#RequestMapping(value="/waterquality/add", method=RequestMethod.POST)
public WaterQuality addWaterQuality(#RequestBody WaterQuality waterQuality) {
waterQuality.setCasestudyList(new HashSet<CaseStudy>());
CaseStudy casestudy = new CaseStudy();
casestudy.setLocation(location);
casestudy.setEquipment(equipment);
casestudy.setIssue(issue);
casestudy.setSolution(solution);
casestudy.setBenefit(benefit);
casestudy.setUpper_dissolved_Oxygen(upper_dissolved_Oxygen);
casestudy.setLower_dissolved_Oxygen(lower_dissolved_Oxygen);
waterQuality.getCasestudyList().add(casestudy);
return waterQualityService.save(waterQuality);
}
Get request for all waterqualities response returns and endless loop of the same results.
[{"waterQualityId":1,"description":"sdfdsf","status":"dsfdsf","dissolved_Oxygen":5.0,"pH":7.0,"temp":72.0,"conductivity":500.0,"publishDate":1472784062000,"dissolvedOxygenalert":[{"caseStudyId":2,"location":null,"equipment":null,"issue":null,"solution":null,"benefit":null,"upper_dissolved_Oxygen":0.0,"lower_dissolved_Oxygen":0.0,"upper_pH":0.0,"lower_pH":0.0,"upper_temp":0.0,"lower_temp":0.0,"upper_conductivity":0.0,"lower_conductivity":0.0,"created":1472784062000,"likes":0,"waterQualityList":[{"waterQualityId":1,"description":"sdfdsf","status":"dsfdsf","dissolved_Oxygen":5.0,"pH":7.0,"temp":72.0,"conductivity":500.0,"publishDate":1472784062000,"dissolvedOxygenalert":[{"caseStudyId":2,"location":null,"equipment":null,"issue":null,"solution":null,"benefit":null,"upper_dissolved_Oxygen":0.0,"lower_dissolved_Oxygen":0.0,"upper_pH":0.0,"lower_pH":0.0,"upper_temp":0.0,"lower_temp":0.0,"upper_conductivity":0.0,"lower_conductivity":0.0,"created":1472784062000,"likes":0,"waterQualityList":
I am able to get data populated to the join table, but it seems to populate endlessly. It happens when the water quality data is added.
It is not clear in code posted, how you are trying to save associated entity. You should persist like this...
WaterQuality waterQuality = new WaterQuality();
//Set other fields too
CaseStudy caseStudy1 = new CaseStudy();
CaseStudy caseStudy2 = new CaseStudy();
CaseStudy caseStudy3 = new CaseStudy();
CaseStudy caseStudy4 = new CaseStudy();
//Set other fileds of case study too
List<CaseStudy> caseStudyList = waterQuality.getCaseStudyList();
caseStudyList.add(caseStudy1);
caseStudyList.add(caseStudy2);
caseStudyList.add(caseStudy3);
caseStudyList.add(caseStudy4);
waterQualityService.save(waterQuality);
If you will assign WaterQuality objects to CaseStudy Entity and save CaseStudy, then associations won't be populated in JoinTable.
And one more important thing, use Set instead of List for Collection.In case of List, Suppose, You already have 100 case study for waterQuality and if you want to delete one of them, Then it will delete entire case studies first and then add all case study again except the deleted one. Use Set if your collection does not contain duplicates. If your collection contains duplicates too, Then use List with index.

Categories

Resources