> PurchaseOrderHeaderDto
package com.assignment.dto;
import java.util.List;
import com.assignment.entity.PurchaseItem;
public class PurchaseOrderHeaderDto{
private List<PurchaseItem> itemList;
public List<PurchaseItem> getItemList() {
return itemList;
}
public void setItemList(List<PurchaseItem> itemList) {
this.itemList = itemList;
}
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getPaymentterms() {
return paymentterms;
}
public void setPaymentterms(String paymentterms) {
this.paymentterms = paymentterms;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
private int ponumber;
private String vendor;
private String paymentterms;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private String companycode;
}
above is the code for the DTO class
> PurchaseOrderHeader
package com.assignment.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.fasterxml.jackson.annotation.JsonBackReference;
#Entity
#Table(name="PurchaseOrderHeader")
/*#FilterDef(name ="poFilter", parameters =#ParamDef(name ="ponumber", type ="int"))
#Filter(name ="poFilter", condition ="ponumber>=:ponumber")
*/
public class PurchaseOrderHeader implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2293787550626038248L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name="ponumber")
private int ponumber;
#JsonBackReference
#OneToMany( fetch = FetchType.EAGER,mappedBy = "purchaseorder",cascade = CascadeType.ALL)
private List<PurchaseItem> itemList;
public List<PurchaseItem> getItemList() {
return itemList;
}
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public void setItemList(List<PurchaseItem> itemList) {
this.itemList = itemList;
}
public Integer getCompanycode() {
return companycode;
}
public void setCompanycode(Integer companycode)
{
this.companycode = companycode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getPaymentterms() {
return paymentterms;
}
public void setPaymentterms(String paymentterms) {
this.paymentterms = paymentterms;
}
#Column(name="companycode")
private Integer companycode;
#Column(name="status")
private String status;
#Column(name="vendor")
private String vendor;
#Column(name="paymentterms")
private String paymentterms;
public PurchaseOrderHeader() {
}
public PurchaseOrderHeader(int ponumber, Integer companycode, String status, String vendor, String paymentterms) {
this.ponumber = ponumber;
this.companycode = companycode;
this.status = status;
this.vendor = vendor;
this.paymentterms = paymentterms;
}
}
above is the code for the DO class
model mapper mapping errors ,Unable to convert String to Integer
DTO class has company code as String and the DO class has the company code
as Integer type when data is passed in json if string value is passed
for company code it should throw 400 bad request error in postman.
NumberFormatException on passing data in postman.
Mysql database used for db transactions.
SEVERE: Servlet.service() for servlet [spring] in context with path [/Pro] threw exception [Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
1) Converter org.modelmapper.internal.converter.NumberConverter#6279a752 failed to convert java.lang.String to java.lang.Integer.
1 error] with root cause
java.lang.NumberFormatException: For input string: "asdfghertyu"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Related
I'm developing a crud API with a post method, when testing this method in my postman it returns the error
2023-02-15T13:34:35.528-03:00 WARN 8792 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<java.lang.Object> com.api.order_control.controllers.OrderController.saveOrder(com.api.order_control.dtos.OrderDto) with 2 errors: [Field error in object 'orderDto' on field 'doorNumber': rejected value [null]; codes [NotBlank.orderDto.doorNumber,NotBlank.doorNumber,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [orderDto.doorNumber,doorNumber]; arguments []; default message [doorNumber]]; default message [must not be blank]] [Field error in object 'orderDto' on field 'block': rejected value [null]; codes [NotBlank.orderDto.block,NotBlank.block,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [orderDto.block,block]; arguments []; default message [block]]; default message [must not be blank]] ]
I couldn't understand why my blank cannot work with this method and why this error. can anybody help me?
model
package com.api.order_control.models;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "restaurant_orders")
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(nullable = false, length = 11)
private String customerName;
#Column(nullable = false, length = 15)
private String phoneNumber;
#Column(nullable = false, length = 25)
private String address;
#Column(nullable = false, length = 10)
private String doorNumber;
#Column(length = 5)
private String block;
#Column(nullable = false, length = 30)
private String orderNote;
#Column(nullable = false)
private Float price;
#Column(nullable = false)
private LocalDateTime registrationDate;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrderNote() {
return orderNote;
}
public void setOrderNote(String order) {
this.orderNote = orderNote;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public LocalDateTime getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDateTime registrationDate) {
this.registrationDate = registrationDate;
}
}
dto pack
package com.api.order_control.dtos;
import jakarta.validation.constraints.NotBlank;
public class OrderDto {
#NotBlank
private String customerName;
#NotBlank
private String phoneNumber;
#NotBlank
private String address;
#NotBlank
private String doorNumber;
#NotBlank
private String block;
#NotBlank
private String orderNote;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String doorNumber() {
return doorNumber;
}
public void doorNumber(String doorName) {
this.doorNumber = doorName;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrderNote() {
return orderNote;
}
public void setOrderNote(String orderNote) {
this.orderNote = orderNote;
}
}
controller with post
package com.api.order_control.controllers;
import com.api.order_control.dtos.OrderDto;
import com.api.order_control.models.OrderModel;
import com.api.order_control.services.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/orders")
public class OrderController {
final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping
public ResponseEntity<Object> saveOrder(#RequestBody #Valid OrderDto orderDto) {
var orderModel = new OrderModel();
BeanUtils.copyProperties(orderDto, orderModel);
orderModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
orderModel.setPrice(70.8f);
return ResponseEntity.status(HttpStatus.CREATED).body(orderService.save(orderModel));
}
}
I had already had a blank error because I was using a float, but in this case "numberDoor" is just a string. What is the reason for this error?
Postman request
{
"customerName": "Ryan",
"phoneNumber": "1 99859 5854",
"address": "St Street Vl 190",
"doorNumber": "5",
"orderNote": "Pepperoni Pizza"
}
It's a validation error.
You don't pass block in your post method, but in DTO this field annotated with #NotBlack
You didn't provide eligible setter for doorNumber. As a result, this field is null in your DTO object, but again, is annotated with #NotBlack. The setter name must be setDoorNumber(String value) for that field
I am working on the CRUD rest API and application is turning on but when I'm trying to make a post request there is a: "status": 404, "error": "Not Found". On the postman, I also add header content-type: application/JSON and requesting at URL: http://localhost:8080/tickets.
Do you know guys how to fix this?
Here is the code.
model:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Tickets {
#Id
#Column
private int ticketid;
#Column
private String title;
#Column
private String description;
#Column
private String creationDate;
#Column
private String severity;
#Column
private String status;
public int getTicketid() {
return ticketid;
}
public void setTicketid(int ticketid) {
this.ticketid = ticketid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
controller:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.service.TicketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class TicketsController {
#Autowired
TicketsService ticketsService;
#GetMapping("/ticket")
private List<Tickets> getAllTickets() {
return ticketsService.getAllTickets();
}
#GetMapping("/ticket/{ticketid}")
private Tickets getTicket(#PathVariable("ticketid")int ticketid) {
return ticketsService.getTicketsById(ticketid);
}
#DeleteMapping("/ticket/{ticketid}")
private void deleteTicket(#PathVariable("ticketid")int ticketid) {
ticketsService.deleteTicket(ticketid);
}
#PostMapping(value = "/tickets")
private int saveTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets.getTicketid();
}
#PutMapping("/tickets")
private Tickets updateTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets;
}
}
service:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.repository.TicketsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class TicketsService {
#Autowired
TicketsRepository ticketsRepository;
public List<Tickets> getAllTickets() {
List<Tickets> tickets = new ArrayList<Tickets>();
ticketsRepository.findAll().forEach(tickets1 -> tickets.add(tickets1));
return tickets;
}
public Tickets getTicketsById(int id) {
return ticketsRepository.findById(id).get();
}
public void saveUpdateTicket(Tickets tickets) {
ticketsRepository.save(tickets);
}
public void deleteTicket(int id) {
ticketsRepository.deleteById(id);
}
public void update(Tickets tickets, int ticketid) {
ticketsRepository.save(tickets);
}
}
repository:
import com.cisco.interview.model.Tickets;
import org.springframework.data.repository.CrudRepository;
public interface TicketsRepository extends CrudRepository<Tickets, Integer> {
}
im trying to make a post request at postman and getting 404 error
Have you specify the POST method in Postman ?
And the body of your request ?
Postam sample
I have an error in class domain Microservice
Oracle dataBase
package hisL3.vnpt.tiepnhan.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import oracle.sql.DATE;
//import org.hibernate.annotations.Table;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Column;
import javax.persistence.Id;
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "his_manager.tgg_quanly_lichhen")
public class Dm_bao_hiem_y_te {
private Integer id;
private Integer id_lichhen;
private Integer mabenhnhan;
private String tenbenhnhan;
private Integer gioitinh;
private String sodienthoai;
private String tenbenhvien;
private Integer songay;
private DATE ngayhen;
private DATE ngaythaotac;
private Integer ngioithaotac;
private Integer guisms;
#Column(name = "ID_LICHHEN", insertable = false, updatable = false)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId_lichhen() {
return id_lichhen;
}
public void setId_lichhen(Integer id_lichhen) {
this.id_lichhen = id_lichhen;
}
public Integer getMabenhnhan() {
return mabenhnhan;
}
public void setMabenhnhan(Integer mabenhnhan) {
this.mabenhnhan = mabenhnhan;
}
public String getTenbenhnhan() {
return tenbenhnhan;
}
public void setTenbenhnhan(String tenbenhnhan) {
this.tenbenhnhan = tenbenhnhan;
}
public Integer getGioitinh() {
return gioitinh;
}
public void setGioitinh(Integer gioitinh) {
this.gioitinh = gioitinh;
}
public String getSodienthoai() {
return sodienthoai;
}
public void setSodienthoai(String sodienthoai) {
this.sodienthoai = sodienthoai;
}
public String getTenbenhvien() {
return tenbenhvien;
}
public void setTenbenhvien(String tenbenhvien) {
this.tenbenhvien = tenbenhvien;
}
public Integer getSongay() {
return songay;
}
public void setSongay(Integer songay) {
this.songay = songay;
}
public DATE getNgayhen() {
return ngayhen;
}
public void setNgayhen(DATE ngayhen) {
this.ngayhen = ngayhen;
}
public DATE getNgaythaotac() {
return ngaythaotac;
}
public void setNgaythaotac(DATE ngaythaotac) {
this.ngaythaotac = ngaythaotac;
}
public Integer getNgioithaotac() {
return ngioithaotac;
}
public void setNgioithaotac(Integer ngioithaotac) {
this.ngioithaotac = ngioithaotac;
}
public Integer getGuisms() {
return guisms;
}
public void setGuisms(Integer guisms) {
this.guisms = guisms;
}
}
Error:
Failed to initialize JPA EntityManagerFactory: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: hisL3.vnpt.tiepnhan.entity.Dm_bao_hiem_y_te column: id_lichhen (should be mapped with insert="false" update="false")
Connection oracle.jdbc.driver.T4CConnection#493325b4 marked as broken because of SQLSTATE(08006), ErrorCode(17002)
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.
When I launch my Spring Hibernate App, I get this error :
Error creating bean with name 'manageUserDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory edusef.dao.ManageUserDAO.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SessionFactory' defined in ServletContext resource [/WEB-INF/application-context.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: edusef.model.Roles, at table: USER, for columns: [org.hibernate.mapping.Column(roles)]
I'm not a real guru on J2EE and this almost my first advanced app. I don't know what is happening there, here is my User and Roles models :
package edusef.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.ManyToOne;
import java.util.Date;
#Entity
#Table (name="USER")
public class User {
private int idUser;
private String NomUser;
private String PrenUser;
private String MailUser;
private String AdressUser;
private int PhoneUser;
private Date DateNaissanceUser;
private int AccountStatus;
private String Password;
private String Login;
private char SexeUser;
private String ImagePath;
private int idRole;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="IDUSER", unique = true, nullable = false)
public int getidUser() { return idUser; }
public void setidUser(int iduser) { this.idUser = iduser; }
#Column(name="NOMUSER", nullable = false)
public String getNomUser() { return NomUser; }
public void setNomUser(String nomUser) { this.NomUser = nomUser; }
#Column(name="PRENUSER", nullable = false)
public String getPrenUser() { return PrenUser; }
public void setPrenUser(String prenUser) { this.PrenUser = prenUser; }
#Column(name="MAILUSER", nullable = false)
public String getMailUser() { return MailUser; }
public void setMailUser(String mailUser) { this.MailUser = mailUser; }
#Column(name="ADRESSUSER", nullable = false)
public String getAdressUser() { return AdressUser; }
public void setAdressUser(String adressUser) { this.AdressUser = adressUser; }
#Column(name="PHONEUSER", nullable = false)
public int getPhoneUser() { return PhoneUser; }
public void setPhoneUser(int phoneUser) { this.PhoneUser = phoneUser; }
#Column(name="DATENAISSANCEUSER", nullable = false)
public Date getDateNaissanceUser() { return DateNaissanceUser; }
public void setDateNaissanceUser(Date dateNaissanceUser) { this.DateNaissanceUser = dateNaissanceUser; }
#Column(name="ACCOUNTSTATUS", nullable = false)
public int getAccountStatus() { return AccountStatus; }
public void setAccountStatus(int accountStatus) { this.AccountStatus = accountStatus; }
#Column(name="PASSWORD", nullable = false)
public String getPassword() { return Password; }
public void setPassword(String password) { this.Password = password; }
#Column(name="LOGIN", nullable = false)
public String getLogin() { return Login; }
public void setLogin(String login) { this.Login = login; }
#Column(name="SEXEUSER", nullable = false)
public char getSexeUser() { return SexeUser; }
public void setSexeUser(char sexeUser) { this.SexeUser = sexeUser; }
#Column(name="IMAGEPATH", nullable = true)
public String getImagePath() { return ImagePath; }
public void setImagePath(String imagePath) { this.ImagePath = imagePath; }
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="IDROLE", nullable=false)
public int getidRole() { return idRole; }
public void setidRole(int idRole) { this.idRole = idRole; }
private Roles roles;
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
#Override
public String toString() {
StringBuffer strBuff = new StringBuffer();
strBuff.append("idUser : ").append(getidUser());
strBuff.append(", NomUser : ").append(getNomUser());
strBuff.append(", PrenUser : ").append(getPrenUser());
strBuff.append(", MailUser : ").append(getMailUser());
strBuff.append(", AdressUser : ").append(getAdressUser());
strBuff.append(", PhoneUser : ").append(getPhoneUser());
strBuff.append(", DateNaissanceUser : ").append(getDateNaissanceUser());
strBuff.append(", AccountStatus : ").append(getAccountStatus());
strBuff.append(", Password : ").append(getPassword());
strBuff.append(", Login : ").append(getLogin());
strBuff.append(", SexeUser : ").append(getSexeUser());
strBuff.append(", ImagePath : ").append(getImagePath());
// strBuff.append(", idRole : ").append(getidRole());
return strBuff.toString();
}
}
Roles :
package edusef.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="ROLES")
public class Roles {
private int idRole;
private String Role;
#Id
#Column(name="IDROLE", unique = true, nullable = false)
public int getIdRole() { return idRole; }
public void setIdRole(int idRole) { this.idRole = idRole; }
#Column(name="ROLES", nullable = false)
public String getRole() { return Role; }
public void setRole(String role) { Role = role; }
}
ManageUserDAO :
package edusef.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import edusef.model.User;
import java.util.List;
#Repository
public class ManageUserDAO {
public #interface ComponentScan {
}
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() { return sessionFactory; }
public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}
public void addUser(User user) {
getSessionFactory().getCurrentSession().save(user);
}
public void deleteUser(User user) {
getSessionFactory().getCurrentSession().delete(user);
}
public void updateUser(User user) {
getSessionFactory().getCurrentSession().update(user);
}
public User getUserById(int id) {
List list = getSessionFactory().getCurrentSession().createQuery("from User where id=?").setParameter(0, id).list();
return (User)list.get(0);
}
public List<User> getUsers() {
List list = getSessionFactory().getCurrentSession().createQuery("from User").list();
return list;
}
}
RolesDAOImpl :
public class RolesDAOImpl implements RolesDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Roles getRoles(int idRole) {
Roles role = (Roles) getCurrentSession().load(Roles.class, idRole);
return role;
}
}
My Logic is that each User has one Role (ManyToOne) and each role can be used by many users. the User.idRole entity should return the idRole of the User and depending on it we test the user role on Spring Security ..
Any help is welcome ! Thanks
You're trying to map an int with #ManyToOne in your User class. You should be mapping a Role instead.
Remove the getIdRole() and setIdRole() methods from this part, they don't belong there.
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="IDROLE", nullable=false)
public int getidRole() { return idRole; }
public void setidRole(int idRole) { this.idRole = idRole; }
private Roles roles;
public Roles getRoles() {
return roles;
}