How we can compare two values of flux using springreactor - java

Currently I am new in reactive programming ,
I have added data in 2 documents, so currently what I am trying to do is to return only those data to client whose tokenIdentifier is same in both document.
Please refer the code below:
I have 2 collection that has
package com.mainApp;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(value = "Token")
public class TokenData {
#Id
private String id;
private String tokenIdentifier;
private Date todayDate;
public TokenData(String id, String tokenIdentifier, Date todayDate) {
super();
this.id = id;
this.tokenIdentifier = tokenIdentifier;
this.todayDate = todayDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTokenIdentifier() {
return tokenIdentifier;
}
public void setTokenIdentifier(String tokenIdentifier) {
this.tokenIdentifier = tokenIdentifier;
}
public Date getTodayDate() {
return todayDate;
}
public void setTodayDate(Date todayDate) {
this.todayDate = todayDate;
}
}
package com.mainApp;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(value = "TURCollection")
public class TURCollection {
#Id
private String id;
private String turIdentifier;
private String tokenIdentifier;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTurIdentifier() {
return turIdentifier;
}
public void setTurIdentifier(String turIdentifier) {
this.turIdentifier = turIdentifier;
}
public String getTokenIdentifier() {
return tokenIdentifier;
}
public void setTokenIdentifier(String tokenIdentifier) {
this.tokenIdentifier = tokenIdentifier;
}
}
I have a controller which will return only those tokenData whose tokenData.getTokenIdentifier() == TURCollection.getTokenIdentifier().
So
#GetMapping(value = "/getAllToken")
public Flux<TokenData> getToken(){
/*List<TokenData> returnData = new ArrayList<TokenData>();
List<TokenData> tokenData = tokenDataRepository.findAll().collectList().block();
List<TURCollection> turCollection = turRepository.findAll().collectList().block();
turCollection.forEach(tur -> {
for(TokenData data : tokenData) {
if(tur.getTokenIdentifier().equals(data.getTokenIdentifier())) {
returnData.add(data);
}
}
});*/
but the block() code is not working in reactive programming
Can anyone help how I can compare values of two flux in reactive way?

You can use a combination of Flux.collectList and Mono.flatMap.
Mono<List<TokenData>> tokenData = tokenDataRepository.findAll().collectList();
Mono<List<TURCollection>> turCollection = turRepository.findAll().collectList();
Mono<List<TokenData>> result = turCollection.flatMap(turs ->
Set<String> ids = turs.stream().map(TURCollection::getId).collect(toSet());
return tokenData.map(tokens ->
tokens.stream().filter(token -> ids.contains(token.getId())).collect(toList())
);
);

Related

Output Spring Boot is reversed in Postman

My problem: when I do an #Post in Postman I get data back from the prices, but not kitten data.
I enter the following:
{
"name": "Frizzle",
"dateOfBirth": "2019-07-27",
"weight": 7.1,
"breed": "Birman",
"firstVaccination": "yes",
"secondVaccination": "yes",
"breedPrice": 8000,
"firstVaccinationPrice": 80.50,
"secondVaccinationPrice": 80.10
}
And this is what I get back in Postman:
{
"id": 3,
"name": null,
"dateOfBirth": null,
"weight": 0.0,
"breed": null,
"firstVaccination": null,
"secondVaccination": null,
"fileUpload": null,
"price": {
"id": 3,
"broadPrice": 8000.0,
"firstVaccinationPrice": 80.5,
"secondVaccinationPrice": 80.1,
"totalPrice": 8160.6
}
}
I've tried changing the code in several places, but I can't figure out why it outputs the price part and not the kitten data part. I want it to output the kitten data. So basically what I want is for him to reverse it, return data of the kittens and give data of the prices that are null.
My files look like this.
Kitten.java
import com.sun.istack.NotNull;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(name = "kittens")
public class Kitten {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
private String name;
#NotNull
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#NotNull
#Column
private double weight;
#NotNull
#Column(name = "breed")
private String breed;
#Column(name = "first_vaccination")
private String firstVaccination;
#Column(name = "second_vaccination")
private String secondVaccination;
#OneToOne(mappedBy = "kitten")
private FileUpload fileUpload;
#OneToOne(fetch = FetchType.LAZY,
mappedBy = "kitten")
private Price price;
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
}
public Kitten() {
}
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 LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public FileUpload getFileUpload() {
return fileUpload;
}
public void setFileUpload(FileUpload fileUpload) {
this.fileUpload = fileUpload;
}
public Price getPrice() {
return price;
}
public void setPrice(Price price) {
this.price = price;
}
}
Price.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.NotNull;
import javax.persistence.*;
#Entity
#Table(name = "prices")
public class Price {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "breed_price")
private double breedPrice;
#Column(name = "first_vaccination_price")
private double firstVaccinationPrice;
#Column(name = "second_vaccination_price")
private double secondVaccinationPrice;
#JsonIgnore
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
orphanRemoval = true)
#JoinColumn(name = "kitten_id")
private Kitten kitten;
public Price() {
}
public Price(double breedPrice, double firstVaccinationPrice, double secondVaccinationPrice) {
this.breedPrice = breedPrice;
this.firstVaccinationPrice = firstVaccinationPrice;
this.secondVaccinationPrice = secondVaccinationPrice;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
public Kitten getKitten() {
return kitten;
}
public void setKitten(Kitten kitten) {
this.kitten = kitten;
}
public Double getTotalPrice() {
return this.getBreedPrice() + this.getFirstVaccinationPrice() + this.getSecondVaccinationPrice();
}
}
KittenBuilder.java
import nl.danielle.cattery.payload.KittenRequest;
import java.time.LocalDate;
public class KittenBuilder {
//Kitten
private String name;
private LocalDate dateOfBirth;
private double weight;
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public KittenBuilder(KittenRequest kittenRequest) {
this.name = kittenRequest.getName();
this.dateOfBirth = kittenRequest.getDateOfBirth();
this.weight = kittenRequest.getWeight();
this.breed = kittenRequest.getBreed();
this.firstVaccination = kittenRequest.getFirstVaccination();
this.secondVaccination = kittenRequest.getSecondVaccination();
this.breedPrice = kittenRequest.getBreedPrice();
this.firstVaccinationPrice = kittenRequest.getFirstVaccinationPrice();
this.secondVaccinationPrice = kittenRequest.getSecondVaccinationPrice();
}
public Kitten buildKitten() {
return new Kitten(name, dateOfBirth, weight, breed, firstVaccination, secondVaccination);
}
public Price buildPrice() {
return new Price(breedPrice, firstVaccinationPrice, secondVaccinationPrice);
}
}
KittenRequest.java
import com.sun.istack.NotNull;
import java.time.LocalDate;
public class KittenRequest {
//Kitten
#NotNull
private String name;
#NotNull
private LocalDate dateOfBirth;
#NotNull
private double weight;
#NotNull
private String breed;
private String firstVaccination;
private String secondVaccination;
//Price
#NotNull
private double breedPrice;
private double firstVaccinationPrice;
private double secondVaccinationPrice;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getFirstVaccination() {
return firstVaccination;
}
public void setFirstVaccination(String firstVaccination) {
this.firstVaccination = firstVaccination;
}
public String getSecondVaccination() {
return secondVaccination;
}
public void setSecondVaccination(String secondVaccination) {
this.secondVaccination = secondVaccination;
}
public double getBreedPrice() {
return breedPrice;
}
public void setBreedPrice(double breedPrice) {
this.breedPrice = breedPrice;
}
public double getFirstVaccinationPrice() {
return firstVaccinationPrice;
}
public void setFirstVaccinationPrice(double firstVaccinationPrice) {
this.firstVaccinationPrice = firstVaccinationPrice;
}
public double getSecondVaccinationPrice() {
return secondVaccinationPrice;
}
public void setSecondVaccinationPrice(double secondVaccinationPrice) {
this.secondVaccinationPrice = secondVaccinationPrice;
}
}
KittenController.java
import nl.danielle.cattery.model.FileUpload;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.payload.ResponseMessage;
import nl.danielle.cattery.service.FileStorageServiceImpl;
import nl.danielle.cattery.service.KittenService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
#RestController
#RequestMapping(value = "/kittens")
public class KittenController {
final KittenService kittenService;
final FileStorageServiceImpl storageService;
public KittenController(KittenService kittenService, FileStorageServiceImpl storageService) {
this.kittenService = kittenService;
this.storageService = storageService;
}
#GetMapping(value = "")
public ResponseEntity<Object> getKittens() {
return ResponseEntity.ok().body(kittenService.getKittens());
}
#GetMapping(value = "/{id}")
public ResponseEntity<Object> getKitten(#PathVariable("id") long id) {
return ResponseEntity.ok().body(kittenService.getKittenById(id));
}
#PostMapping(value = "/add")
public ResponseEntity<Object> saveKitten(#RequestBody KittenRequest kitten) {
long newId = kittenService.saveKitten(kitten);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(newId).toUri();
return ResponseEntity.created(location).build();
}
#PutMapping(value = "/{id}")
public ResponseEntity<Object> updateKitten(#PathVariable("id") long id, #RequestBody KittenRequest kitten) {
kittenService.updateKitten(id, kitten);
return ResponseEntity.noContent().build();
}
#PutMapping(value = "/{id}/price")
public ResponseEntity<Object> updatePrice(#PathVariable("id") long id, #RequestBody KittenRequest price) {
kittenService.updatePrice(id, price);
return ResponseEntity.noContent().build();
}
#DeleteMapping(value = "/{id}")
public ResponseEntity<Object> deleteKitten(#PathVariable("id") long id) {
kittenService.deleteKitten(id);
return ResponseEntity.noContent().build();
}
#PostMapping("/upload/kittenid/{id}")
public ResponseEntity<ResponseMessage> uploadFile(#PathVariable long id, #RequestParam("file") MultipartFile file) {
try {
storageService.store(file, id);
String message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
String message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
#GetMapping("/download/{id}")
public ResponseEntity<byte[]> getFileById(#PathVariable("id") String id) {
FileUpload fileUpload = storageService.getFileById(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
.body(fileUpload.getData());
}
}
KittenService.java
package nl.danielle.cattery.service;
import nl.danielle.cattery.exceptions.DatabaseErrorException;
import nl.danielle.cattery.exceptions.RecordNotFoundException;
import nl.danielle.cattery.model.Kitten;
import nl.danielle.cattery.model.KittenBuilder;
import nl.danielle.cattery.model.Price;
import nl.danielle.cattery.payload.KittenRequest;
import nl.danielle.cattery.repository.KittenRepository;
import nl.danielle.cattery.repository.PriceRepository;
import org.springframework.stereotype.Service;
import java.util.Collection;
#Service
public class KittenServiceImpl implements KittenService {
final KittenRepository kittenRepository;
final PriceRepository priceRepository;
public KittenServiceImpl(KittenRepository kittenRepository, PriceRepository priceRepository) {
this.kittenRepository = kittenRepository;
this.priceRepository = priceRepository;
}
#Override
public Collection<Kitten> getKittens() {
return kittenRepository.findAll();
}
#Override
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException();
}
return kittenRepository.findById(id).orElse(null);
}
#Override
public long saveKitten(KittenRequest kittenRequest) {
Kitten newKitten = new KittenBuilder(kittenRequest).buildKitten();
Price newPrice = new KittenBuilder(kittenRequest).buildPrice();
Price savedPrice = priceRepository.save(newPrice);
newKitten.setPrice(savedPrice);
newPrice.setKitten(newKitten);
return kittenRepository.save(newKitten).getId();
}
#Override
public void updateKitten(long id, KittenRequest kitten) {
if (kittenRepository.existsById(id)) {
try {
Kitten existingKitten = kittenRepository.findById(id).orElse(null);
existingKitten.setName(kitten.getName());
existingKitten.setDateOfBirth(kitten.getDateOfBirth());
existingKitten.setWeight(kitten.getWeight());
existingKitten.setBreed(kitten.getBreed());
existingKitten.setFirstVaccination(kitten.getFirstVaccination());
existingKitten.setSecondVaccination(kitten.getSecondVaccination());
kittenRepository.save(existingKitten);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void updatePrice(long id, KittenRequest price) {
if (priceRepository.existsById(id)) {
try {
Price existingPrice = priceRepository.findById(id).orElse(null);
existingPrice.setBreedPrice(price.getBreedPrice());
existingPrice.setFirstVaccinationPrice(price.getFirstVaccinationPrice());
existingPrice.setSecondVaccinationPrice(price.getSecondVaccinationPrice());
priceRepository.save(existingPrice);
} catch (Exception ex) {
throw new DatabaseErrorException();
}
} else {
throw new RecordNotFoundException();
}
}
#Override
public void deleteKitten(long id) {
kittenRepository.deleteById(id);
}
}
I have a lot to say about your code here, but let's see what's the main problem here. The problem is simple if you look at your KittenBuilder you create a Kitten using this builder but your Kitten constructor is empty.
public Kitten(String name, LocalDate dateOfBirth, double weight, String breed, String firstVaccination, String secondVaccination) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.weight = weight;
this.breed = breed;
this.firstVaccination = firstVaccination;
this.secondVaccination = secondVaccination;
}
This will populate the Kitten object and you're ready to go.
Some advices about your code
If you wonder why it's saving the null values when you specified the null constraints is that recent version of spring boot don't include the validation starter in the web starter, you have to include it yourself.
In you pom.xml add the following dependecy:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
And you have to include the annotation #Transactional to your services to make your operations atomic, for example in your create kitten method you want to persist the price and the kitten atomically.
#Service
#Transactional
class KittenServiceImpl implementes ...
And one the best practices also, is to not use your entites directly in your controllers, use DTO (Data Transfer Object), so you map the properties you want from your entity to your DTO (this way you can include only your kitten properties and leave the price entity).
And last bonus:
public Kitten getKittenById(long id) {
if (!kittenRepository.existsById(id)) {
throw new RecordNotFoundException("");
}
return kittenRepository.findById(id).orElse(null);
}
This can be simplified to:
public Kitten getKittenById(long id) {
return kittenRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
}

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.

How to order descending the data in hibernate

I want to order the data descending in hibernate,
but not working at all,
this is my code,
#SuppressWarnings("unchecked")
#Override
public List<MPNValas> listAllMPNValas() throws Exception{
DetachedCriteria criteria = DetachedCriteria.forClass(MPNValas.class);
criteria.addOrder(Order.desc("ID"));
List<MPNValas> mpnvalasList = getHibernateTemplate().findByCriteria(criteria);
return mpnvalasList;
}
this is my controller,
#RequestMapping("/admin/mpn-valas.html")
public ModelAndView listMPNValas(ModelMap model)throws Exception
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String sessionUser = user.getUsername();
try{
UserAdmin dataUser = userService.get(sessionUser);
model.addAttribute("userData", dataUser);
} catch(Exception e){
e.printStackTrace();
}
ModelAndView mav = new ModelAndView("mpnvalas");
List<MPNValas> mpnvalas = mpnvalasService.listAllMPNValas();
mav.addObject("mpnvalas", mpnvalas);
return mav;
}
and this is the class,
package prod.support.model.gwprod;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="LOOKUP")
public class MPNValas {
private Integer ID;
private String TIPE;
private String KODE_PERUSAHAAN;
private String CODE;
private String NAME;
private String VALUE;
#Id
#Column(name="ID", unique=true, nullable=false)
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
#Column(name="TIPE")
public String getTIPE() {
return TIPE;
}
public void setTIPE(String TIPE) {
this.TIPE = TIPE;
}
#Column(name="KODE_PERUSAHAAN")
public String getKODE_PERUSAHAAN() {
return KODE_PERUSAHAAN;
}
public void setKODE_PERUSAHAAN(String KODE_PERUSAHAAN) {
this.KODE_PERUSAHAAN = KODE_PERUSAHAAN;
}
#Column(name="CODE")
public String getCODE() {
return CODE;
}
public void setCODE(String CODE) {
this.CODE = CODE;
}
#Column(name="NAME")
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME;
}
#Column(name="VALUE")
public String getVALUE() {
return VALUE;
}
public void setVALUE(String VALUE) {
this.VALUE = VALUE;
}
/**
* #param args
*/
}
and this the list of data
that I miss something??
any help will be pleasure :))
You miss nothing, just note that the argument to the desc method is case sensitive and should match the name of the attribute to sort by.
Criteria criteria = session.createCriteria(Foo.class, "FOO");
criteria.addOrder(Order.desc("id"));

ebean model update not permanent

Good day! I'm having a problem when updating an entity. When I click the "update" button, the changes are saved. However, when I go a different page, the recently changed (or added) items are there but the old items (that should be changed or removed) are also there. Particularly the relatedTags (the name and notes are updating just fine). Why is it not persistent or permanent?
Here is where the updating happens.
Form<Tag> filledForm = tagForm.fill(Tag.find.byId(id)).bindFromRequest();
Tag editedTag = RelatedTag.findTag(id);
if(filledForm.hasErrors()) {
return badRequest(editTagForm.render(user, editedTag, filledForm, tags));
}
else {
List<RelatedTag> relatedTagsAlloc = new ArrayList<RelatedTag>();
java.util.Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] relatedTags = map.get("relatedTags.tag.name");
String[] relationship = map.get("relatedTags.relationship");
String[] relatedNotes = map.get("relatedTags.relatedNotes");
if (relatedTags != null) {
for (int i = 0; i < relatedTags.length; i++) {
if (RelatedTag.exists(relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "))) {
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
} else {
Tag unknown = new Tag(relatedTags[i], "");
Tag.create(unknown);
relatedTagsAlloc.add(RelatedTag.findByLabel(
relatedTags[i].trim().toLowerCase().replaceAll("\\s+", " "), relationship[i], relatedNotes[i].trim()));
}
}
editedTag.getRelatedTags().clear();
}
editedTag.setName(filledForm.get().getName().toLowerCase().replaceAll("\\s+", " "));
editedTag.setRelatedTags(relatedTagsAlloc);
editedTag.update();
Application.log(user, editedTag, action);
writeToFile(editedTag);
return ok(summary.render(user, editedTag));
}
And here are the models:
Tag model:
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class Tag extends Model{
#Id
private int id;
#Required
#MaxLength(value=100)
#Column(unique=true)
private String name;
#MaxLength(value=200)
private String notes;
#OneToMany(cascade=CascadeType.ALL)
public List<RelatedTag> relatedTags = new ArrayList<RelatedTag>();
#Version
public Timestamp lastUpdate;
public static Finder<Integer, Tag> find = new Finder(Int.class, Tag.class);
public Tag() {
}
public Tag(String name, String notes){
this.name = name;
this.notes = notes;
}
public Tag(int id, String name, String notes, List<RelatedTag> relatedTags) {
this.id = id;
this.name = name;
this.notes = notes;
this.relatedTags = relatedTags;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public List<RelatedTag> getRelatedTags() {
return relatedTags;
}
public void setRelatedTags(List<RelatedTag> relatedTags) {
this.relatedTags = relatedTags;
}
public static List<Tag> all() {
return find.all();
}
public static void create(Tag tag){
tag.save();
}
public static void delete(int id){
find.ref(id).delete();
}
public static void update(int id, Tag tag) {
tag.update(id); // updates this entity, by specifying the entity ID
}
public static boolean exists(Tag newTag) {
for(Tag allTags : Tag.find.all()) {
if(allTags.getName().equals(newTag.getName()))
return true;
}
return false;
}
}
RelatedTag model
package models;
import java.sql.Timestamp;
import java.util.*;
import javax.persistence.*;
import javax.validation.*;
import play.data.Form;
import play.data.validation.Constraints.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import scala.Int;
#Entity
public class RelatedTag extends Model {
#Id
public int rtID;
private int id; //same as Tag's id
private String relationship;
private String relatedNotes;
#Version
public Timestamp lastUpdate;
public RelatedTag() {}
public RelatedTag(int id, String relationship, String relatedNotes) {
this.id = id;
this.relationship = relationship;
this.relatedNotes = relatedNotes;
}
public void setId(int id){
this.id = id;
}
public void setRelationship(String relationship){
this.relationship = relationship;
}
public void setRelatedNotes(String relatedNotes) {
this.relatedNotes = relatedNotes;
}
public int getId(){
return id;
}
public String getRelationship(){
return relationship;
}
public String getRelatedNotes() {
return relatedNotes;
}
public static void create(List<RelatedTag> rt){
((Model) rt).save();
}
public static boolean exists(String tagRelated) {
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName()))
return true;
}
return false;
}
public static RelatedTag findByLabel(String tagRelated, String relation, String relatedNotes) {
RelatedTag relatedTag = null;
for(Tag tag : Tag.find.all()) {
if(tagRelated.equals(tag.getName())) {
relatedTag = new RelatedTag(tag.getId(), relation, relatedNotes);
}
}
return relatedTag;
}
public static Tag findTag(int id) {
for(Tag tag : Tag.find.all()) {
if(id == tag.getId())
return tag;
}
return null;
}
}
What have I been doing wrong? Please help me fix this. Thank you very much!

hibernate many-to-many table mapping with extra fields as a list - Java classes?

I am quite interested in a Hibernate mapping such as the Order/Product/LineItem described here:
http://docs.jboss.org/hibernate/stable/core/reference/en/html/example-mappings.html#example-mappings-customerorderproduct
The documentation seems quite thorough, but I am a bit unclear on the semantics of the Java classes that one would create...
Any hints much appreciated.
Thank you!
Misha
Using that example, you would have classes that looked like the following:
import java.util.HashSet;
import java.util.Set;
public class Customer {
private String name = null;
private Set<Order> orders = new HashSet<Order>();
private long id = 0;
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 Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Order {
private long id = 0;
private Date date = null;
private Customer customer = null;
private List<LineItem> lineItems = new ArrayList<LineItem>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<LineItem> getLineItems() {
return lineItems;
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
}
public class LineItem {
private int quantity = 0;
private Product product = null;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
public class Product {
private long id = 0;
private String serialNumber = null;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
}
If you create the tables as per the structure in the example, that should set you up.
They show the UML and the class members in the diagram.
A Customer can have zero to many Order objects (Set).
An Order has at least one to many LineItem objects. {List).
A LineItem entry corresponds to a Product. So LineItem has exactly one Product object.
Not sure what your question is?

Categories

Resources