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.
Related
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.
Need help when trying to save through this method, my hibernate debug doesn't show any error, no one error catch in this method
it is not committed, already try everything includes saveAndFlush() from JPARepositiry, all possible annotation, check whole my algorithm and logic. I thought it's related to my PostgreSQL configuration or my bidirectional relationship between related entities. But still, nothing showed up on my table in the database
#RequestMapping(value = "/save-pegawai-status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> savePlanningPegawaiStatus(#Valid #RequestBody PlanningPegawaiStatusVO vo,
HttpServletRequest request) {
try {
Map<String, Object> result = servicePermohonanStatus.savePlanningPegawaiStatus(vo);
if (CommonUtil.isNotNullOrEmpty(result.get("noRec"))) {
mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
} else {
return RestUtil.getJsonResponse(result, HttpStatus.OK);
}
} catch (ServiceVOException e) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", e.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, e.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
} catch (JpaSystemException jse) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", jse.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, jse.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
} catch (Exception exp) {
LOGGER.error("Got exception {} when savePlanningPegawaiStatus", exp.getMessage());
addHeaderMessage(Constants.MessageInfo.ERROR_MESSAGE, exp.getMessage());
return RestUtil.getJsonHttptatus(HttpStatus.CONFLICT, mapHeaderMessage);
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="ListTanggalCuti_T")
public class ListTanggalCuti extends BaseTransaction{
#Caption(value="tgl")
#Column(name="tgl", nullable=true)
private Date tgl;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Boolean approvalStatus;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Planning Pegawai Status")
#JoinColumn(name="ObjectPlanningPegawaiStatusFK")
private PlanningPegawaiStatus planningPegawaiStatus;
#Column(name="ObjectPlanningPegawaiStatusFK", insertable=false, updatable=false)
private String planningPegawaiStatusId;
public Date getTgl() {
return tgl;
}
public void setTgl(Date tgl) {
this.tgl = tgl;
}
public Boolean getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Boolean approvalStatus) {
this.approvalStatus = approvalStatus;
}
public PlanningPegawaiStatus getPlanningPegawaiStatus() {
return planningPegawaiStatus;
}
public void setPlanningPegawaiStatus(PlanningPegawaiStatus planningPegawaiStatus) {
this.planningPegawaiStatus = planningPegawaiStatus;
}
public String getPlanningPegawaiStatusId() {
return planningPegawaiStatusId;
}
public void setPlanningPegawaiStatusId(String planningPegawaiStatusId) {
this.planningPegawaiStatusId = planningPegawaiStatusId;
}
}
package com.jasamedika.medifirst2000.entities;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.jasamedika.medifirst2000.base.BaseTransaction;
import com.jasamedika.medifirst2000.helper.Caption;
#Entity
#Table(name="PlanningPegawaiStatus_T")
public class PlanningPegawaiStatus extends BaseTransaction{
#Caption(value="No Planning")
#Column(name="NoPlanning", length=15, nullable=true)
private String noPlanning;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Pegawai")
#JoinColumn(name="ObjectPegawaiFk")
private Pegawai pegawai;
// #ManyToOne(fetch=FetchType.LAZY)
// #Caption(value="Object Jabatan Cuti")
// #JoinColumn(name="ObjectJabatanCutiFk")
// private Jabatan jabatanCuti;
#Column(name="ObjectPegawaiFk", nullable=true, insertable=false, updatable=false)
private Integer pegawaiId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Plan")
#JoinColumn(name="ObjectStatusPegawaiPlanFk")
private StatusPegawai statusPegawaiPlan;
#Column(name="ObjectStatusPegawaiPlanFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiPlanId;
#OneToMany(cascade=CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = "planningPegawaiStatus", orphanRemoval=true)
private Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Departemen")
#JoinColumn(name="ObjectDepartemenFk")
private Departemen departemen;
#Column(name="ObjectDepartemenFk", nullable=true, insertable=false, updatable=false)
private Integer departemenId;
#Caption(value="Deskripsi Status Pegawai Plan")
#Column(name="DeskripsiStatusPegawaiPlan", length=1000, nullable=true)
private String deskripsiStatusPegawaiPlan;
#Caption(value="Keterangan Lainya Plan")
#Column(name="KeteranganLainyaPlan", length=1000, nullable=true)
private String keteranganLainyaPlan;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object No SK")
#JoinColumn(name="ObjectNoSkFk")
private SuratKeputusan noSk;
#Column(name="ObjectNoSkFk", nullable=true, insertable=false, updatable=false)
private Integer noSkId;
#ManyToOne(fetch=FetchType.LAZY)
#Caption(value="Object Status Pegawai Exec")
#JoinColumn(name="ObjectStatusPegawaiExecFk")
private StatusPegawai statusPegawaiExec;
#Column(name="ObjectStatusPegawaiExecFk", nullable=true, insertable=false, updatable=false)
private Integer statusPegawaiExecId;
#Caption(value="Deskripsi Status Pegawai Exec")
#Column(name="DeskripsiStatusPegawaiExec", length=1000, nullable=true)
private String deskripsiStatusPegawaiExec;
#Caption(value="Keterangan Lainya Exec")
#Column(name="KeteranganLainyaExec", length=1000, nullable=true)
private String keteranganLainyaExec;
#Caption(value="Tgl Pengajuan")
#Column(name="TglPengajuan", nullable=true)
private Date tglPengajuan;
#Caption(value="Tgl Keputusan")
#Column(name="TglKeputusan", nullable=true)
private Date tglKeputusan;
#Caption(value="Approval Status")
#Column(name="ApprovalStatus", nullable=true)
private Integer approvalStatus;
#Caption(value="jumlahHari")
#Column(name="jumlahHari", nullable=true)
private Integer jumlahHari;
// #Caption(value="keterangan")
// #Column(name="keterangan", nullable=true)
// private String keterangan;
#Caption(value="Jenis Perawatan")
#Column(name="jenisPerawatan", nullable=true)
private Integer jenisPerawatan;
#Caption(value="Alamat Selama Cuti")
#Column(name="alamatCuti", nullable=true)
private String alamatCuti;
#Caption(value="Nomor Telepon")
#Column(name="nomorTelepon", nullable=true)
private String nomorTelepon;
#Caption(value="Nomor Surat Tugas")
#Column(name="noSuratTugas", nullable=true)
private String noSuratTugas;
#Caption(value="Nomor Nota Dinas")
#Column(name="noNotaDinas", nullable=true)
private String noNotaDinas;
#Caption(value="Tgl Nota Dinas")
#Column(name="TglNotaDinas", nullable=true)
private Date tglNotaDinas;
#Caption(value="Alamat Tugas Dinas")
#Column(name="alamatTugas", nullable=true)
private String alamatTugas;
#ManyToOne(optional=true,fetch=FetchType.LAZY)
#Caption(value="Object Jabatan Pemberi Nota Dinas")
#JoinColumn(name="ObjectJabatanPemberiNotaDinasFk", nullable=true)
private Jabatan jabatanPemberiNotaDinas;
#Column(name="ObjectJabatanPemberiNotaDinasFk", nullable=true, insertable=false, updatable=false)
private Integer jabatanIdPemberiNotaDinas;
#Caption(value="is Cuti Luar Negeri")
#Column(name="isCutiLuarNegeri", nullable=true)
private Boolean isCutiLuarNegeri;
public String getNoPlanning() {
return noPlanning;
}
public void setNoPlanning(String noPlanning) {
this.noPlanning = noPlanning;
}
public Pegawai getPegawai() {
return pegawai;
}
public void setPegawai(Pegawai pegawai) {
this.pegawai = pegawai;
}
public Integer getPegawaiId() {
return pegawaiId;
}
public void setPegawaiId(Integer pegawaiId) {
this.pegawaiId = pegawaiId;
}
// public Jabatan getJabatanCuti() {
// return jabatanCuti;
// }
// public void setJabatanCuti(Jabatan jabatanCuti) {
// this.jabatanCuti = jabatanCuti;
// }
public StatusPegawai getStatusPegawaiPlan() {
return statusPegawaiPlan;
}
public void setStatusPegawaiPlan(StatusPegawai statusPegawaiPlan) {
this.statusPegawaiPlan = statusPegawaiPlan;
}
public Integer getStatusPegawaiPlanId() {
return statusPegawaiPlanId;
}
public void setStatusPegawaiPlanId(Integer statusPegawaiPlanId) {
this.statusPegawaiPlanId = statusPegawaiPlanId;
}
public Departemen getDepartemen() {
return departemen;
}
public void setDepartemen(Departemen departemen) {
this.departemen = departemen;
}
public Integer getDepartemenId() {
return departemenId;
}
public void setDepartemenId(Integer departemenId) {
this.departemenId = departemenId;
}
public String getDeskripsiStatusPegawaiPlan() {
return deskripsiStatusPegawaiPlan;
}
public void setDeskripsiStatusPegawaiPlan(String deskripsiStatusPegawaiPlan) {
this.deskripsiStatusPegawaiPlan = deskripsiStatusPegawaiPlan;
}
public String getKeteranganLainyaPlan() {
return keteranganLainyaPlan;
}
public void setKeteranganLainyaPlan(String keteranganLainyaPlan) {
this.keteranganLainyaPlan = keteranganLainyaPlan;
}
public SuratKeputusan getNoSk() {
return noSk;
}
public void setNoSk(SuratKeputusan noSk) {
this.noSk = noSk;
}
public Integer getNoSkId() {
return noSkId;
}
public void setNoSkId(Integer noSkId) {
this.noSkId = noSkId;
}
public StatusPegawai getStatusPegawaiExec() {
return statusPegawaiExec;
}
public void setStatusPegawaiExec(StatusPegawai statusPegawaiExec) {
this.statusPegawaiExec = statusPegawaiExec;
}
public Integer getStatusPegawaiExecId() {
return statusPegawaiExecId;
}
public void setStatusPegawaiExecId(Integer statusPegawaiExecId) {
this.statusPegawaiExecId = statusPegawaiExecId;
}
public String getDeskripsiStatusPegawaiExec() {
return deskripsiStatusPegawaiExec;
}
public void setDeskripsiStatusPegawaiExec(String deskripsiStatusPegawaiExec) {
this.deskripsiStatusPegawaiExec = deskripsiStatusPegawaiExec;
}
public String getKeteranganLainyaExec() {
return keteranganLainyaExec;
}
public void setKeteranganLainyaExec(String keteranganLainyaExec) {
this.keteranganLainyaExec = keteranganLainyaExec;
}
public Date getTglPengajuan() {
return tglPengajuan;
}
public void setTglPengajuan(Date tglPengajuan) {
this.tglPengajuan = tglPengajuan;
}
public Date getTglKeputusan() {
return tglKeputusan;
}
public void setTglKeputusan(Date tglKeputusan) {
this.tglKeputusan = tglKeputusan;
}
public Integer getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Integer approvalStatus) {
this.approvalStatus = approvalStatus;
}
public Integer getJumlahHari() {
return jumlahHari;
}
public void setJumlahHari(Integer jumlahHari) {
this.jumlahHari = jumlahHari;
}
public Set<ListTanggalCuti> getListTanggal() {
return listTanggal;
}
public void setListTanggal(Set<ListTanggalCuti> listTanggal) {
this.listTanggal = listTanggal;
}
// public String getKeterangan() {
// return keterangan;
// }
// public void setKeterangan(String keterangan) {
// this.keterangan = keterangan;
// }
public Integer getJenisPerawatan() {
return jenisPerawatan;
}
public void setJenisPerawatan(Integer jenisPerawatan) {
this.jenisPerawatan = jenisPerawatan;
}
public String getAlamatCuti() {
return alamatCuti;
}
public void setAlamatCuti(String alamatCuti) {
this.alamatCuti = alamatCuti;
}
public String getNomorTelepon() {
return nomorTelepon;
}
public void setNomorTelepon(String nomorTelepon) {
this.nomorTelepon = nomorTelepon;
}
public String getNoSuratTugas() {
return noSuratTugas;
}
public void setNoSuratTugas(String noSuratTugas) {
this.noSuratTugas = noSuratTugas;
}
public String getNoNotaDinas() {
return noNotaDinas;
}
public void setNoNotaDinas(String noNotaDinas) {
this.noNotaDinas = noNotaDinas;
}
public Date getTglNotaDinas() {
return tglNotaDinas;
}
public void setTglNotaDinas(Date tglNotaDinas) {
this.tglNotaDinas = tglNotaDinas;
}
public String getAlamatTugas() {
return alamatTugas;
}
public void setAlamatTugas(String alamatTugas) {
this.alamatTugas = alamatTugas;
}
public Jabatan getJabatanPemberiNotaDinas() {
return jabatanPemberiNotaDinas;
}
public void setJabatanPemberiNotaDinas(Jabatan jabatanPemberiNotaDinas) {
this.jabatanPemberiNotaDinas = jabatanPemberiNotaDinas;
}
public Integer getJabatanIdPemberiNotaDinas() {
return jabatanIdPemberiNotaDinas;
}
public void setJabatanIdPemberiNotaDinas(Integer jabatanIdPemberiNotaDinas) {
this.jabatanIdPemberiNotaDinas = jabatanIdPemberiNotaDinas;
}
public Boolean getIsCutiLuarNegeri() {
return isCutiLuarNegeri;
}
public void setIsCutiLuarNegeri(Boolean isCutiLuarNegeri) {
this.isCutiLuarNegeri = isCutiLuarNegeri;
}
}
#Override
#Transactional
public Map<String, Object> savePlanningPegawaiStatus(PlanningPegawaiStatusVO vo) {
Map<String, Object> result = new HashMap<>();
boolean statusTanggalPermohonan = validateTanggalPermohonan(vo.getListTanggal(), vo.getPegawai().getId());
if (CommonUtil.isNotNullOrEmpty(statusTanggalPermohonan) && !statusTanggalPermohonan) {
result.put("bisaCuti", statusTanggalPermohonan);
result.put("status", "Tanggal Permohonan sudah pernah diajukan!"); //Validasi tanggal permohonan yang sudah diajukan
return result;
} else {
Integer day = 0;
if (CommonUtil.isNotNullOrEmpty(vo)) {
PlanningPegawaiStatus planningPegawaiStatus = planningPegawaiStatusConverter.transferVOToModel(vo,
new PlanningPegawaiStatus());
String noPlanning = noUsulan().get("noUsulan").toString();
if (CommonUtil.isNotNullOrEmpty(noPlanning)) {
planningPegawaiStatus.setNoPlanning(noPlanning);
planningPegawaiStatus.setStatusEnabled(true);
if (CommonUtil.isNotNullOrEmpty(vo.getStatusPegawaiPlan())) {
planningPegawaiStatus.setStatusPegawaiPlan(
statusPegawaiConverter.transferVOToModel(vo.getStatusPegawaiPlan(), new StatusPegawai()));
}
if (CommonUtil.isNotNullOrEmpty(vo.getJabatanPemberiNotaDinas())) {
planningPegawaiStatus.setJabatanPemberiNotaDinas(
jabatanConverter.transferVOToModel(vo.getJabatanPemberiNotaDinas(), new Jabatan()));
}
planningPegawaiStatus.setApprovalStatus(0);
if (CommonUtil.isNotNullOrEmpty(vo.getPegawai())) {
planningPegawaiStatus
.setPegawai(pegawaiConverter.transferVOToModel(vo.getPegawai(), new Pegawai()));
}
Set<ListTanggalCuti> listTanggal = new HashSet<ListTanggalCuti>();
for (ListTanggalCutiVO date : vo.getListTanggal()) {
day++;
ListTanggalCuti tanggal = listTanggalConverter.transferVOToModel(date, new ListTanggalCuti());
tanggal.setPlanningPegawaiStatus(planningPegawaiStatus);
tanggal.setStatusEnabled(true);
listTanggal.add(tanggal);
}
planningPegawaiStatus.setJumlahHari(day);
planningPegawaiStatus.setListTanggal(listTanggal);
if (CommonUtil.isNotNullOrEmpty(vo.getDeskripsiStatusPegawaiPlan())) {
planningPegawaiStatus.setDeskripsiStatusPegawaiPlan(vo.getDeskripsiStatusPegawaiPlan());
}
if (CommonUtil.isNotNullOrEmpty(vo.getKeteranganLainyaPlan())) {
planningPegawaiStatus.setKeteranganLainyaPlan(vo.getKeteranganLainyaPlan());
}
//Set Alamat Cuti dan No Telepon
planningPegawaiStatus.setAlamatCuti(vo.getAlamatCuti());
planningPegawaiStatus.setNomorTelepon(vo.getNomorTelepon());
if (CommonUtil.isNotNullOrEmpty(vo.getAlamatTugas())) {
planningPegawaiStatus.setAlamatTugas(vo.getAlamatTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoSuratTugas())) {
planningPegawaiStatus.setNoSuratTugas(vo.getNoSuratTugas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getNoNotaDinas())) {
planningPegawaiStatus.setNoNotaDinas(vo.getNoNotaDinas());
}
if (CommonUtil.isNotNullOrEmpty(vo.getTglNotaDinas())) {
planningPegawaiStatus.setTglNotaDinas(vo.getTglNotaDinas());
}
planningPegawaiStatus.setIsCutiLuarNegeri(vo.getIsCutiLuarNegeri());
if (CommonUtil.isNotNullOrEmpty(planningPegawaiStatus)) {
List<String> listTgl = new ArrayList<>();
planningPegawaiStatus.setStatusEnabled(true);
PlanningPegawaiStatus planningPegawaiStatusResult = planningPegawaiStatusDao
.save(planningPegawaiStatus);
for (ListTanggalCuti listTanggalCuti : planningPegawaiStatusResult.getListTanggal()) {
listTgl.add(listTanggalCuti.getNoRec());
}
result.put("listTgl", listTgl);
result.put("noRec", planningPegawaiStatusResult.getNoRec());
result.put("bisaCuti", statusTanggalPermohonan);
}
}
}
return result;
}
}
PlanningPegawaiStatusVO and ListTanggalCutiVO just related value object class, transferVOToModel() is a method for data access from value object class to model
I'm finally realized that sometimes its commit and sometimes it isn't. And then when it isn't inserted to the database, also return with HttpStatus.CREATED an ERROR_MESSAGE like could not extract ResultSet from GenericJDBCException but it does not come from catch
I created spring boot project where I am making rest application. I have used My SQL database and I am using spring data. There is one method which adds orders based on customer id. So I am not able to figure out it will work based on spring data query or custom query and how it will be?
I have attached required codes only,
Customer.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customers")
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cust_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int custIDPK;
#Column(name = "billing_city")
private String billingCity;
#Column(name = "billing_country")
private String billingCountry;
#Column(name = "billing_state")
private String billingState;
#Column(name = "billing_street")
private String billingStreet;
#Column(name = "billing_zip")
private String billingZip;
private String company;
#Column(name = "display_name")
private String displayName;
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "other_details")
private String otherDetails;
#Column(name = "print_on_check_as")
private String printOnCheckAs;
#Column(name = "shipping_city")
private String shippingCity;
#Column(name = "shipping_country")
private String shippingCountry;
#Column(name = "shipping_state")
private String shippingState;
#Column(name = "shipping_street")
private String shippingStreet;
#Column(name = "shipping_zip")
private String shippingZip;
private String suffix;
private String title;
// bi-directional many-to-one association to Order
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Order> orders;
public Customer() {
}
public int getCustIDPK() {
return this.custIDPK;
}
public void setCustIDPK(int cust_ID_PK) {
this.custIDPK = cust_ID_PK;
}
public String getBillingCity() {
return this.billingCity;
}
public void setBillingCity(String billingCity) {
this.billingCity = billingCity;
}
public String getBillingCountry() {
return this.billingCountry;
}
public void setBillingCountry(String billingCountry) {
this.billingCountry = billingCountry;
}
public String getBillingState() {
return this.billingState;
}
public void setBillingState(String billingState) {
this.billingState = billingState;
}
public String getBillingStreet() {
return this.billingStreet;
}
public void setBillingStreet(String billingStreet) {
this.billingStreet = billingStreet;
}
public String getBillingZip() {
return this.billingZip;
}
public void setBillingZip(String billingZip) {
this.billingZip = billingZip;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getOtherDetails() {
return this.otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getPrintOnCheckAs() {
return this.printOnCheckAs;
}
public void setPrintOnCheckAs(String printOnCheckAs) {
this.printOnCheckAs = printOnCheckAs;
}
public String getShippingCity() {
return this.shippingCity;
}
public void setShippingCity(String shippingCity) {
this.shippingCity = shippingCity;
}
public String getShippingCountry() {
return this.shippingCountry;
}
public void setShippingCountry(String shippingCountry) {
this.shippingCountry = shippingCountry;
}
public String getShippingState() {
return this.shippingState;
}
public void setShippingState(String shippingState) {
this.shippingState = shippingState;
}
public String getShippingStreet() {
return this.shippingStreet;
}
public void setShippingStreet(String shippingStreet) {
this.shippingStreet = shippingStreet;
}
public String getShippingZip() {
return this.shippingZip;
}
public void setShippingZip(String shippingZip) {
this.shippingZip = shippingZip;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
Order.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "orders")
#NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "order_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int order_ID_PK;
#Column(name = "custom_message")
private String customMessage;
#Temporal(TemporalType.DATE)
#Column(name = "delivery_due_date")
private Date deliveryDueDate;
#Temporal(TemporalType.DATE)
#Column(name = "invoice_creation_date")
private Date invoiceCreationDate;
#Temporal(TemporalType.DATE)
#Column(name = "payment_due_date")
private Date paymentDueDate;
// bi-directional many-to-one association to Customer
#ManyToOne
#JoinColumn(name = "cust_ID_FK")
private Customer customer;
// bi-directional many-to-many association to Product
#ManyToMany(mappedBy = "orders")
private List<Product> products;
public Order() {
}
public int getOrder_ID_PK() {
return this.order_ID_PK;
}
public void setOrder_ID_PK(int order_ID_PK) {
this.order_ID_PK = order_ID_PK;
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
public Date getDeliveryDueDate() {
return this.deliveryDueDate;
}
public void setDeliveryDueDate(Date deliveryDueDate) {
this.deliveryDueDate = deliveryDueDate;
}
public Date getInvoiceCreationDate() {
return this.invoiceCreationDate;
}
public void setInvoiceCreationDate(Date invoiceCreationDate) {
this.invoiceCreationDate = invoiceCreationDate;
}
public Date getPaymentDueDate() {
return this.paymentDueDate;
}
public void setPaymentDueDate(Date paymentDueDate) {
this.paymentDueDate = paymentDueDate;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
OrderOperation.java
package com.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.model.Order;
public interface OrderOperation extends JpaRepository<Order, Long> {
#Query("SELECT c.orders FROM Customer c where c.custIDPK = :id")
public List<Order> findOrderbyID(#Param("id") int id);
}
CustomerController.java
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
ICutomerService customerDAO;
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = { "/", "" }, method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllCustomer() {
return new ResponseEntity(customerDAO.getAllCustomer(), HttpStatus.ACCEPTED);
}
#RequestMapping(value = "/{CustomerById}", method = RequestMethod.GET, produces = { "application/json" })
public Customer getCustomerbyId(#PathVariable("CustomerById") String cid) {
return customerDAO.findCustomerById(Integer.parseInt(cid));
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "{CustomerById}/order", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllOrder(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getOrdersbyId(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(value = "order/{CustomerById}/product", method = RequestMethod.GET, produces = {
"application/json" })
public ResponseEntity<?> getAllProduct(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getProductsById(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addCustomer(#RequestBody Customer c) {
boolean flag = customerDAO.addCustomer(c);
if (flag)
return new ResponseEntity(HttpStatus.CREATED);
else
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{CustomerById}/orders", method = RequestMethod.POST)
public ResponseEntity<?> addOrders(#PathVariable("CustomerById") String cid, #RequestBody Order c) {
// c.getCustomer().setCustIDPK(Integer.parseInt(cid));
boolean flag = customerDAO.addOrder(c);
if (flag) {
return new ResponseEntity(HttpStatus.CREATED);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
How should I design this addOrders method?
If you are using Spring Data then you will need to create a CrudRepository for each table you which to access. The CrudRepository allows you to easily manipulate data in your table using standard ORM practices. Here is a link with more details.
For more detailed info on how to use Spring Data check out this wonderful guide. This guide has become indispensable when working with Spring Data.
There are many options to this but i have used below approach so hope it helps you. The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
#Query(value = "select o.* from customer c inner join order o on c.customer_id = o.customer_id where o. = ?1", nativeQuery = true)
Please write sql according to your requirement.
I edited this
I have an Employee class and a Sell class.
Sell has a
#ManyToOne
relationship with Employee .
So I need an employee list order by sells, in order to search for the best month seller, but I need the sells quantity too.
I made a Service class in order to do this.
I have the right beans to create the lists, that's not a problem. The problem is that I don't know how to get 2 different list out of a function or maybe use a vector or something like that.
I made my own research before doing this but there is knowledge I don't have or understand at all.
I put some domain code:
Employee
package germanAcosta.electronicaDonPepe.dominio;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
#SuppressWarnings("serial")
#Entity
public class Empleado implements Serializable{
#Id
private Integer dni;
private String password;
private String nombre;
private String apellido;
#ManyToMany // 1 o +
private List <Comision> comision;
#OneToMany(cascade=CascadeType.ALL)
private List <Premio> premio;
private String tipo;
public Empleado(){
}
public Empleado(Integer dni, String password, String nombre, String apellido, List<Comision> comision,
List<Premio> premio, String tipo) {
super();
this.dni = dni;
this.password = password;
this.nombre = nombre;
this.apellido = apellido;
this.comision = comision;
this.premio = premio;
this.tipo = tipo;
}
public Integer getDni() {
return dni;
}
public void setDni(Integer dni) {
this.dni = dni;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public List<Comision> getComision() {
return comision;
}
public void setComision(List<Comision> comision) {
this.comision = comision;
}
public List<Premio> getPremio() {
return premio;
}
public void setPremio(List<Premio> premio) {
this.premio = premio;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
}
Sell
package germanAcosta.electronicaDonPepe.dominio;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
#SuppressWarnings("serial")
#Entity
public class Venta implements Serializable {
#Id
#GeneratedValue
private Integer numero_factura;
#ManyToOne
private Empleado empleado;
#OneToMany(cascade = CascadeType.ALL)
private List<Producto> productos = new ArrayList<Producto>();
private Date fechaDeIngreso;
public Venta() {
}
public Venta(Integer numero_factura, Empleado empleado, List<Producto> productos, Date fechaDeIngreso) {
super();
this.numero_factura = numero_factura;
this.empleado = empleado;
this.productos = productos;
this.fechaDeIngreso = fechaDeIngreso;
}
#Override
public boolean equals(Object objeto) {
if (objeto == null) {
return false;
}
if (this == objeto) {
return true;
}
if (objeto instanceof Venta) {
Venta otraVenta = (Venta) objeto;
if (otraVenta.getNumero_factura() == this.numero_factura) {
return true;
}
}
return false;
}
public Integer getNumero_factura() {
return numero_factura;
}
public void setNumero_factura(Integer numero_factura) {
this.numero_factura = numero_factura;
}
public Empleado getEmpleado() {
return empleado;
}
public void setEmpleado(Empleado empleado) {
this.empleado = empleado;
}
public List<Producto> getProductos() {
return productos;
}
public void setProductos(List<Producto> productos) {
this.productos = productos;
}
public Date getFechaDeIngreso() {
return fechaDeIngreso;
}
public void setFechaDeIngreso(Date fechaDeIngreso) {
this.fechaDeIngreso = fechaDeIngreso;
}
}
Thanks in advance.
You don't want to sort the sizes of opinions. You want to sort the movies, by their size of opinions:
movies.sort(Comparator.comparingInt(movie -> movie.getOpinions().size());
You have not posted actual code atleast for domain classes, but What you are looking for is I guess
Employee emp= emList.stream().max((a,b)-> a.getSellList().size()-b.getSellList().size());
System.out.pritntf("best seller : %s , quantity : %d", emp.getName(),empty.getSellList().size());
Major edit 1 :
After i got idea of domain i am changing my code as below.I have used my own domain classes i.e. POJOs instead of JPA. I have tested this code and works fine.
package com.grs.stackOverFlow.pack02;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.PrimitiveIterator.OfDouble;
import java.util.stream.Collectors;
public class Pack02Demo{
public static void main(String []args){
List<Sell> sells = Sell.createSampleSellList(10);
Map<Employee, List<Sell>> map = sells.stream().collect(Collectors.groupingBy(Sell::getEmp));
System.out.println(map);
Employee som=null;
for(Entry<Employee, List<Sell>> entry: map.entrySet()){
if(som==null){
som=entry.getKey();
}else{
som=map.get(som).size()>entry.getValue().size()?som:(Employee) entry.getKey();
}
}
System.out.printf("Seller of month id : %d , number of sells : %s",som.getId(),map.get(som).size());
}
}
class Sell{
private int id;
private Employee emp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public String toString(){
return String.format("{sell.id : %d, emp.id: %d %n }", id,emp.getId());
}
public static List<Sell> createSampleSellList(int listSize){
List<Employee> employees=Employee.createSampleEmpList(listSize);
List<Sell> sells=new ArrayList<>(listSize);
for(int i=1; i<=listSize; i++){
int id= (int)(Math.random() * employees.size()-1);
Sell sell=new Sell();
sell.setId(i);
sell.setEmp(employees.get(id));
sells.add(sell);
}
return sells;
}
}
class Employee {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Employee(Integer id) {
super();
this.id = id;
}
public String toString(){
return String.format("{employee, id : %d }", id);
}
public boolean equals(Object object){
if(object instanceof Employee){
Employee emp=(Employee)object;
return this.id==emp.getId();
}
else
return false;
}
public int hashCode(){
return new Integer(id).toString().length();
}
public static List<Employee> createSampleEmpList(int size){
List<Employee> employees=new ArrayList<>(size);
for(int i=1; i<=size; i++){
Employee employee=new Employee(i);
employees.add(employee);
}
return employees;
}
}
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!