How to retrieve data from ligneCommandeDto and pass it to lignebpdto to generate dynamically a lignebpService from ligneCommandeService if affercter() is true.
the affercter() method for checking if the isAffected attribute is true, if that I call the genererbp() methode , this methode create a ligneBp so I need to fill il with data from ligneCommandeDTO.
package org.backend.gcmd.service;
import org.backend.gcmd.dto.LigneBpDTO;
import org.backend.gcmd.dto.LigneCommandeDTO;
import org.backend.gcmd.entity.LigneCommandeEntity;
import org.backend.gcmd.exceptions.technical.ObjectNotFoundException;
import org.backend.gcmd.mapper.LigneCommandeMapper;
import org.backend.gcmd.repository.LigneCommandeRepository;
import org.backend.gcmd.validator.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
#Service
#Transactional
public class LigneCommandeService {
#Autowired
private LigneCommandeRepository ligneCommandeRepository;
#Autowired
private LigneCommandeMapper ligneCommandeMapper;
#Autowired
private LigneBpService ligneBpService;
private LigneBpDTO ligneBpDTO;
#Autowired
private LigneBpMapper ligneBpMapper;
public LigneCommandeDTO findById(Long id) {
Validate.notNull(id, "id mus be not null");
Optional<LigneCommandeEntity> entity = ligneCommandeRepository.findById(id);
if (entity.isPresent()) {
return ligneCommandeMapper.convertToDto(entity.get());
} else {
throw new ObjectNotFoundException("LigneCommandeDTO not found");
}
}
public LigneCommandeDTO save(LigneCommandeDTO dto) {
Validate.notNull(dto, "LigneCommandeDTO must be not null");
LigneCommandeEntity entity = ligneCommandeMapper.convertToEntity(dto);
LigneCommandeEntity saved = ligneCommandeRepository.save(entity);
return ligneCommandeMapper.convertToDto(saved);
}
public LigneCommandeDTO update(LigneCommandeDTO dto) {
Validate.notNull(dto, "LigneCommandeDTO must be not null");
Validate.notNull(dto.getId(), "LigneCommandeDTO id must be not null");
findById(dto.getId());
LigneCommandeEntity entity = ligneCommandeMapper.convertToEntity(dto);
LigneCommandeEntity saved = ligneCommandeRepository.save(entity);
return ligneCommandeMapper.convertToDto(saved);
}
public Page<LigneCommandeDTO> findAllByDeletedFalse(Pageable pageable) {
Page<LigneCommandeEntity> page = ligneCommandeRepository.findAllByDeletedFalse(pageable);
return ligneCommandeMapper.convertToPageDto(page);
}
public LigneCommandeDTO affecter(Long id, Boolean isAffected) {
Validate.notNull(id, "LigneCommandeDTO must be not null");
Validate.notNull(isAffected, "LigneCommandeDTO id must be not null");
LigneCommandeDTO lcdto = findById(id);
lcdto.setIsAffected(isAffected);
update(lcdto);
genererbp();
return null;
}
public LigneBpDTO genererbp(LigneCommandeDTO ligneCommandeDTO) {
if (ligneCommandeDTO.getIsAffected()) {
return ligneBpService.findAllByDeletedFalse((Pageable) ligneBpDTO)
.stream()
.map(ligneBpMapper::convertToDto)
.collect(toList());
}
return null;
}
}
the mapper class
package org.backend.gcmd.mapper;
import org.springframework.data.domain.Page;
import java.util.List;
public interface Mapper<D, E> {
Page<D> convertToPageDto(Page<E> page);
D convertToDto(E entity);
E convertToEntity(D dto);
List<D> convertToDtoList(List<E> entities);
List<E> convertToEntitiesList(List<D> entities);
}
package org.backend.gcmd.mapper;
import org.backend.gcmd.dto.LigneBpDTO;
import org.backend.gcmd.entity.LigneBpEntity;
import org.backend.gcmd.repository.BulltinPrestationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
#Component
public class LigneBpMapper implements Mapper<LigneBpDTO, LigneBpEntity> {
#Autowired
BulltinPrestationRepository bulltinprestationRepository;
#Override
public Page<LigneBpDTO> convertToPageDto(Page<LigneBpEntity> page) {
return page.map(this::convertToDto);
}
#Override
public LigneBpDTO convertToDto(LigneBpEntity entity) {
LigneBpDTO dto = new LigneBpDTO();
dto.setId(entity.getId());
dto.setDate(entity.getDate());
dto.setHeure(entity.getHeure());
dto.setNombre(entity.getNombre());
dto.setPrestation(entity.getPrestation());
dto.setProduit(entity.getProduit());
dto.setSensTrafic(entity.getSensTrafic());
dto.setTarifUnifie(entity.getTarifUnifie());
dto.setTcConv(entity.getTcConv());
dto.setTcSuppl(entity.getTcSuppl());
dto.setTonnageMinimum(entity.getTonnageMinimum());
dto.setTonnageReel(entity.getTonnageReel());
return dto;
}
#Override
public LigneBpEntity convertToEntity(LigneBpDTO dto) {
LigneBpEntity entity = new LigneBpEntity();
entity.setId(dto.getId());
entity.setDate(dto.getDate());
entity.setHeure(dto.getHeure());
entity.setNombre(dto.getNombre());
entity.setPrestation(dto.getPrestation());
entity.setProduit(dto.getProduit());
entity.setSensTrafic(dto.getSensTrafic());
entity.setTarifUnifie(dto.getTarifUnifie());
entity.setTcConv(dto.getTcConv());
entity.setTcSuppl(dto.getTcSuppl());
entity.setTonnageMinimum(dto.getTonnageMinimum());
entity.setTonnageReel(dto.getTonnageReel());
return entity;
}
#Override
public List<LigneBpDTO> convertToDtoList(List<LigneBpEntity> entities) {
return entities.stream().map(this::convertToDto).collect(Collectors.toCollection(ArrayList::new));
}
#Override
public List<LigneBpEntity> convertToEntitiesList(List<LigneBpDTO> dtos) {
return dtos.stream().map(this::convertToEntity).collect(Collectors.toCollection(ArrayList::new));
}
}
controller
package org.backend.gcmd.controller;
import org.backend.gcmd.dto.LigneBpDTO;
import org.backend.gcmd.dto.LigneCommandeDTO;
import org.backend.gcmd.service.LigneBpService;
import org.backend.gcmd.service.LigneCommandeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/api/gcmd/v1/ligneCommandes")
public class LigneCommandeController {
#Autowired
private LigneCommandeService ligneCommandeService;
#GetMapping("{id}")
public ResponseEntity<LigneCommandeDTO> findById(#PathVariable Long id) {
LigneCommandeDTO ligneCommandeDTO = ligneCommandeService.findById(id);
return ResponseEntity.status(HttpStatus.OK).body(ligneCommandeDTO);
}
#PostMapping
public ResponseEntity<LigneCommandeDTO> save(#RequestBody LigneCommandeDTO ligneCommandeDTO) {
return ResponseEntity.status(HttpStatus.CREATED).body(ligneCommandeService.save(ligneCommandeDTO));
}
#PutMapping("{id}")
public ResponseEntity<LigneCommandeDTO> update(#PathVariable Long id,
#RequestBody LigneCommandeDTO ligneCommandeDTO) {
ligneCommandeDTO.setId(id);
return ResponseEntity.status(HttpStatus.ACCEPTED).body(ligneCommandeService.update(ligneCommandeDTO));
}
#GetMapping
public ResponseEntity<Page<LigneCommandeDTO>> findAllByDeletedFalse(Pageable pageable) {
return ResponseEntity.status(HttpStatus.OK).body(ligneCommandeService.findAllByDeletedFalse(pageable));
}
}
Related
I'm learning Java and as part of it, trying to develop a Spring Boot API that communicates with MongoDB Atlas cluster. I'm trying to write an API that would return items based on the price range value where min and max values are provided dynamically. Please help me understand where am I doing a mistake by going through the code below. I strongly feel it has to do with #Query and #PathVariable, I feel #RequestParam should be used in place of #PathVariable, however, I'm not sure what to use in place of #Query in the repository.
Here is the code of the repository
package com.webshoppingbackend.springboot.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.webshoppingbackend.springboot.model.WebShoppingItem;
public interface WebShoppingRepository extends MongoRepository<WebShoppingItem, String> {
#Query("{category:?0}")
List<WebShoppingItem> getItemsByCategory(String category);
#Query("{brand:?0}")
List<WebShoppingItem> getItemsByBrand(String brand);
#Query("{price:{$lt:?0,$gt:?1}}")
List<WebShoppingItem> getItemsBasedOnPrice(long higherPrice, long lowerPrice);
}
Here is the code of the controller
package com.webshoppingbackend.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.webshoppingbackend.springboot.model.WebShoppingItem;
import com.webshoppingbackend.springboot.services.WebShoppingService;
#RestController
#RequestMapping("/webshopping")
public class WebShoppingController {
#Autowired
private WebShoppingService service;
#GetMapping
public List<WebShoppingItem> getAllItems() {
return service.getWebShoppingItems();
}
#GetMapping("/{itemId}")
public WebShoppingItem getItem(#PathVariable String itemId) {
return service.getItemById(itemId);
}
#GetMapping("/category/{category}")
public List<WebShoppingItem> getItemsByCategory(#PathVariable String category) {
return service.getItemsByCategory(category);
}
#GetMapping("/brand/{brand}")
public List<WebShoppingItem> getItemsByBrand(#PathVariable String brand) {
return service.getItemsByBrand(brand);
}
#GetMapping("/{price}")
public List<WebShoppingItem> getItemsBasedOnPriceRange(#PathVariable long higherPrice,
#PathVariable long lowerPrice) {
return service.getItemsBasedOnPriceRange(higherPrice, lowerPrice);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public WebShoppingItem addItem(#RequestBody WebShoppingItem webShoppingItem) {
return service.addToWebShoppingItems(webShoppingItem);
}
#PutMapping
public WebShoppingItem modifyItem(#RequestBody WebShoppingItem webShoppingItem) {
return service.updateWebShoppingItem(webShoppingItem);
}
#DeleteMapping("/{itemId}")
public String deleteItem(#PathVariable String itemId) {
return service.deleteWebShoppingItem(itemId);
}
}
Here is the code in the service provider
package com.webshoppingbackend.springboot.services;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.webshoppingbackend.springboot.model.WebShoppingItem;
import com.webshoppingbackend.springboot.repository.WebShoppingRepository;
#Service
public class WebShoppingService {
#Autowired
private WebShoppingRepository repository;
// CRUD
public WebShoppingItem addToWebShoppingItems(WebShoppingItem webShoppingItem) {
webShoppingItem.setItemId(UUID.randomUUID().toString().split("-")[0]);
return repository.save(webShoppingItem);
}
public List<WebShoppingItem> getWebShoppingItems() {
return repository.findAll();
}
public WebShoppingItem getItemById(String itemId) {
return repository.findById(itemId).get();
}
public List<WebShoppingItem> getItemsByCategory(String category) {
return repository.getItemsByCategory(category);
}
public List<WebShoppingItem> getItemsByBrand(String brand) {
return repository.getItemsByBrand(brand);
}
public List<WebShoppingItem> getItemsBasedOnPriceRange(long higherPrice, long lowerPrice) {
return repository.getItemsBasedOnPrice(higherPrice, lowerPrice);
}
public WebShoppingItem updateWebShoppingItem(WebShoppingItem webShoppingItem) {
WebShoppingItem itemToBeUpdated = repository.findById(webShoppingItem.getItemId()).get();
itemToBeUpdated.setCategory(webShoppingItem.getCategory());
itemToBeUpdated.setProductName(webShoppingItem.getProductName());
itemToBeUpdated.setImageSource(webShoppingItem.getImageSource());
itemToBeUpdated.setBrand(webShoppingItem.getBrand());
itemToBeUpdated.setPrice(webShoppingItem.getPrice());
itemToBeUpdated.setRating(webShoppingItem.getRating());
itemToBeUpdated.setShippingCharges(webShoppingItem.getShippingCharges());
itemToBeUpdated.setProductDetails(webShoppingItem.getProductDetails());
return repository.save(itemToBeUpdated);
}
public String deleteWebShoppingItem(String itemId) {
repository.deleteById(itemId);
return "Deleted Web Shopping Item";
}
}
Here is the request I'm sending through Talend API Tester to test my code.
I'm trying to build an API with Spring Boot, but I keep getting an error when dealing with #OneToMany entities. The Bean seem to not be able to get an entity I'm referencing by ID through the JSON from the database and constructing it to insert into the other entity. Sounds complicated, so here's the code for everything and the error. I googled and googled and couldn't find a fitting answer to my specific situation.
Entity Turma:
package com.residencia.academia.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "turma")
public class Turma {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_turma")
private Integer idTurma;
#Column(name = "horario")
private Date horarioTurma;
#Column(name = "duracao")
private Integer duracaoTurma;
#Column(name = "data_inicio")
private Date dataInicioTurma;
#Column(name = "data_fim")
private Date dataFimTurma;
#ManyToOne
#JoinColumn(name = "id_instrutor", referencedColumnName = "id_instrutor")
private Instrutor instrutor;
public Integer getIdTurma() {
return idTurma;
}
public void setIdTurma(Integer idTurma) {
this.idTurma = idTurma;
}
public Date getHorarioTurma() {
return horarioTurma;
}
public void setHorarioTurma(Date horarioTurma) {
this.horarioTurma = horarioTurma;
}
public Integer getDuracaoTurma() {
return duracaoTurma;
}
public void setDuracaoTurma(Integer duracaoTurma) {
this.duracaoTurma = duracaoTurma;
}
public Date getDataInicioTurma() {
return dataInicioTurma;
}
public void setDataInicioTurma(Date dataInicioTurma) {
this.dataInicioTurma = dataInicioTurma;
}
public Date getDataFimTurma() {
return dataFimTurma;
}
public void setDataFimTurma(Date dataFimTurma) {
this.dataFimTurma = dataFimTurma;
}
public Instrutor getInstrutor() {
return instrutor;
}
public void setInstrutor(Instrutor instrutor) {
this.instrutor = instrutor;
}
}
Turma's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.service.TurmaService;
#RestController
#RequestMapping("/turma")
public class TurmaController {
#Autowired
private TurmaService turmaService;
#GetMapping
public ResponseEntity<List<Turma>> findAll() {
return ResponseEntity.ok().body(turmaService.findAllTurma());
}
#GetMapping("/{id}")
public ResponseEntity<Turma> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(turmaService.findByIdTurma(id));
}
#PostMapping
public Turma save(#RequestBody Turma turma) {
return turmaService.saveTurma(turma);
}
#PutMapping
public Turma update(#RequestBody Turma turma) {
return turmaService.updateTurma(turma);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
turmaService.deleteTurma(id);
}
}
Turma's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.repository.TurmaRepository;
#Service
public class TurmaService {
#Autowired
private TurmaRepository turmaRepository;
public List<Turma> findAllTurma() {
return turmaRepository.findAll();
}
public Turma findByIdTurma(Integer id) {
return turmaRepository.findById(id).get();
}
public Turma saveTurma(Turma turma) {
return turmaRepository.save(turma);
}
public Turma updateTurma(Turma turma) {
return turmaRepository.save(turma);
}
public void deleteTurma(Integer id) {
turmaRepository.deleteById(id);
}
public void deleteTurma(Turma turma) {
turmaRepository.delete(turma);
}
}
Turma's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Turma;
public interface TurmaRepository extends JpaRepository<Turma, Integer> {
}
Entity Instrutor:
package com.residencia.academia.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "instrutor")
public class Instrutor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_instrutor")
private Integer idInstrutor;
#Column(name = "rg")
private Integer rgInstrutor;
#Column(name = "nome")
private String nomeInstrutor;
#Column(name = "nascimento")
private Date dataNascimentoInstrutor;
#Column(name = "titulacao")
private Integer titulacaoInstrutor;
#OneToMany(mappedBy = "instrutor")
private List<Turma> turmaList;
public Integer getIdInstrutor() {
return idInstrutor;
}
public void setIdInstrutor(Integer idInstrutor) {
this.idInstrutor = idInstrutor;
}
public Integer getRgInstrutor() {
return rgInstrutor;
}
public void setRgInstrutor(Integer rgInstrutor) {
this.rgInstrutor = rgInstrutor;
}
public String getNomeInstrutor() {
return nomeInstrutor;
}
public void setNomeInstrutor(String nomeInstrutor) {
this.nomeInstrutor = nomeInstrutor;
}
public Date getDataNascimentoInstrutor() {
return dataNascimentoInstrutor;
}
public void setDataNascimentoInstrutor(Date dataNascimentoInstrutor) {
this.dataNascimentoInstrutor = dataNascimentoInstrutor;
}
public Integer getTitulacaoInstrutor() {
return titulacaoInstrutor;
}
public void setTitulacaoInstrutor(Integer titulacaoInstrutor) {
this.titulacaoInstrutor = titulacaoInstrutor;
}
public List<Turma> getTurmaList() {
return turmaList;
}
public void setTurmaList(List<Turma> turmaList) {
this.turmaList = turmaList;
}
}
Instrutor's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.service.InstrutorService;
#RestController
#RequestMapping("/instrutor")
public class InstrutorController {
#Autowired
private InstrutorService instrutorService;
#GetMapping
public ResponseEntity<List<Instrutor>> findAll() {
return ResponseEntity.ok().body(instrutorService.findAllInstrutor());
}
#GetMapping("/{id}")
public ResponseEntity<Instrutor> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(instrutorService.findByIdInstrutor(id));
}
#PostMapping
public Instrutor save(#RequestBody Instrutor instrutor) {
return instrutorService.saveInstrutor(instrutor);
}
#PutMapping
public Instrutor update(#RequestBody Instrutor instrutor) {
return instrutorService.updateInstrutor(instrutor);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
instrutorService.deleteInstrutor(id);
}
}
Instrutor's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.repository.InstrutorRepository;
#Service
public class InstrutorService {
#Autowired
private InstrutorRepository instrutorRepository;
public List<Instrutor> findAllInstrutor() {
return instrutorRepository.findAll();
}
public Instrutor findByIdInstrutor(Integer id) {
return instrutorRepository.findById(id).get();
}
public Instrutor saveInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public Instrutor updateInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public void deleteInstrutor(Integer id) {
instrutorRepository.deleteById(id);
}
public void deleteInstrutor(Instrutor instrutor) {
instrutorRepository.delete(instrutor);
}
}
Instrutor's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Instrutor;
public interface InstrutorRepository extends JpaRepository<Instrutor, Integer> {
}
JSON Structure:
{
"horarioTurma": "2022-06-29T18:00:00",
"duracaoTurma": 60,
"dataInicioTurma": "2022-06-29",
"dataFimTurma": "2022-07-29",
"instrutor": 1
}
HTTP Response:
400 Bad Request
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.residencia.academia.entity.Instrutor` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
Any help is appreciated!
I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:
D:\>curl -G localhost:8080/demo/first?=Biagio
{"timestamp":"2020-10-04T22:46:35.996+00:00","status":404,"error":"Not Found","message":"","path":"/demo/first"}
And to each of my POST / Add requests like this ERROR:
D:\>curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni#gmail.com -d surname=Jackie
{"timestamp":"2020-10-04T22:40:51.928+00:00","status":404,"error":"Not Found","message":"","path":"/demo/add"}
Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now
AccessingDataMysqlApplication.java
package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}
MainController.java
package com.example.accessingdatamysql.rest;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;
#RestController
#RequestMapping("/demo")
public class MainController {
#Autowired
private UserService userService;
#Transactional
//#RequestMapping(value = "/add/", method = RequestMethod.POST)
#PostMapping(path="/demo/add")
public String addNewUser(#PathVariable("name") String name, #PathVariable("email") String email,
#PathVariable("surname") String surname) {
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "User Saved in DB";
}
#SuppressWarnings({ "rawtypes", "unchecked" })
//#RequestMapping(value = "/fetchUser/{name}", method = RequestMethod.GET)
#GetMapping("/demo/first")
public ResponseEntity<UserDto> fetchUser(#PathVariable("name") String name) {
System.out.println(name);
try {
UserDto namefound = userService.findFirstByName(name);
System.out.println("Name found");
ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println("User not found");
return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
}
}
}
UserService.java
package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
#Service
public interface UserService {
UserDto findFirstByName(String name);
void create(UserDto user);
}
UserServiceImpl.java
package com.example.accessingdatamysql.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
UserMapper mapper;
#Override
public UserDto findFirstByName(String name) {
UserEntity entity = userRepository.findFirstByName(name);
return mapper.toDtoMapper(entity);
}
#Override
public void create(UserDto user) {
UserEntity entity = mapper.toEntityMapper(user);
userRepository.create(entity);
}
}
UserMapper.java
package com.example.accessingdatamysql.util;
import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
#Mapper(componentModel = "spring")
public interface UserMapper {
public UserEntity toEntityMapper (UserDto user);
public UserDto toDtoMapper (UserEntity userEntity);
}
UserRepository.java
package com.example.accessingdatamysql.repo;
import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;
#Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);
}
UserRepositoryImpl.java
package com.example.accessingdatamysql.service;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
#Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public UserEntity findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteria = builder.createQuery(UserEntity.class);
Root<UserEntity> root = criteria.from(UserEntity.class);
criteria.select(root).where(builder.equal(root.get("name"), name));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<UserEntity> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
#Override
// per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}
}
UserDto.java
package com.example.accessingdatamysql.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class UserDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7621330660870602403L;
/**
*
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
private Timestamp timestamp;
private String email;
private String surname;
}
If you need I can also insert User.java and the pom, but the pom has no problems as the dependencies are all correct.
You have an additional demo in your path descriptions for GET and POST methods, you should remove it:
#GetMapping("/demo/first")
#PostMapping(path = "/demo/first")
It should be :
#GetMapping("/first")
#PostMapping(path = "/first")
This because you have already defined demo in the RequestMapping annotation in the class level.
im using UUID in my application as Primary Key i have problem whene find data by id give me exception error.
this is Note Class
package com.example.demo.model;
import java.util.Date;
import java.util.UUID;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
#AutoConfigurationPackage
#Entity
public class Note {
#Id
#GeneratedValue( strategy = GenerationType.AUTO,generator = "pg-uuid")
#GenericGenerator(name = "pg-uuid",strategy = "uuid2")
private UUID id;
private String title;
private String text;
#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.MERGE)
private Notebook notebook;
private Date lastModifiedOn;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Notebook getNotebook() {
return notebook;
}
public void setNotebook(Notebook notebook) {
this.notebook = notebook;
}
public Date getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(Date lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
this is NoteController
package com.example.demo.controller;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.MyMapper;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.Repository.NoteRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
#RestController
#RequestMapping("/api/note")
#CrossOrigin
public class NoteController {
#Autowired
NoteRepository noteRepository;
#Autowired
NoteBookRepository notebookRepository;
#Autowired
MyMapper maper;
#GetMapping("/all")
public List<NoteViewModle> getAllNote(){
List<Note> list = this.noteRepository.findAll();
List<NoteViewModle> noteViewModles = (List<NoteViewModle>) list.stream().map(note ->maper.convertToNodeViewModel(note)).collect(Collectors.toList());
return noteViewModles;
}
#GetMapping("/byId/{id}")
public NoteViewModle getNotreById(#PathVariable("id") UUID id) {
System.out.println(id);
Note note = this.noteRepository.findById(id).orElse(null);
if(note == null)
{
System.out.println("In If");
throw new EntityNotFoundException();
}
NoteViewModle modle = maper.convertToNodeViewModel(note);
return modle;
}
#GetMapping("/byNoteBook/{notebookId}")
public List<Note> getNotesByNoteBook(#PathVariable("notebookId") String id)
{
return this.noteRepository.findAllByNotebook(this.notebookRepository.findById(UUID.fromString(id)).orElse(new Notebook()));
}
#PostMapping("/add")
public Note save(#RequestBody NoteViewModle modle)
{
Note note = maper.convertToNodeEntity(modle);
return this.noteRepository.save(note);
}
#DeleteMapping("/deltebyId/{id}")
public void deleteNoteById(#PathVariable("id") String id) {
this.noteRepository.deleteById(UUID.fromString(id));
}
}
this is MyMapper to mape the json data
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
import com.example.demo.view.NotebookViewModel;
#Component
public class MyMapper {
#Autowired
NoteBookRepository bookRepository;
public NoteViewModle convertToNodeViewModel(Note entity) {
NoteViewModle modle = new NoteViewModle();
modle.setId(entity.getId().toString());
modle.setTitle(entity.getTitle());
modle.setText(entity.getText());
modle.setNoteBookId(entity.getNotebook().getId().toString());
modle.setData(entity.getLastModifiedOn().toString());
return modle;
}
public Note convertToNodeEntity(NoteViewModle viewModle) {
Note note = new Note();
note.setTitle(viewModle.getTitle());
note.setText(viewModle.getText());
//note.setLastModifiedOn(new SimpleDateFormat("dd/MM/yyyy").parse(viewModle.getData()));
//Notebook notebook = bookRepository.findById(UUID.fromString(viewModle.getId())).orElse(new Notebook());
return note;
}
public NotebookViewModel convertToNotebookViewModel(Notebook entity)
{
NotebookViewModel viewModel = new NotebookViewModel();
viewModel.setId(entity.getId().toString());
viewModel.setName(entity.getName());
viewModel.setNumOfNote(entity.getNotes().size());
return viewModel;
}
public Notebook convertToNotebookEntity(NotebookViewModel model) {
Notebook notebook = new Notebook();
notebook.setId(UUID.fromString(model.getId()));
notebook.setName(model.getName());
return notebook;
}
}
this is repositry class
package com.example.demo.Repository;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
#Repository
public interface NoteRepository extends JpaRepository<Note, UUID> {
List<Note> findAllByNotebook(Notebook notebook);
}
this is error is appears org.springframework.dao.EmptyResultDataAccessException: No class com.example.demo.model.Notebook entity with id 7e83b195-eb81-4752-a6fa-a5206c9eb1c6 exists!
Is there any possibility to validate StandardMultipartHttpServletRequest using standard #Valid annotation and custom Validator?
I've implemented such validator, annotated method param in controller the validator is not invoked.
I've figured it out myself. To make it work you need a DTO:
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
#Getter
#Setter
public class NewOrderFilesDTO {
List<MultipartFile> files;
}
Then, a validator:
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import static org.springframework.util.CollectionUtils.isEmpty;
#Component
public class NewOrderFilesValidator implements Validator {
private static final String MIME_TYPE_PDF = "application/pdf";
private static final long ALLOWED_SIZE = 3 * 1024 * 1024;
#Override
public void validate(Object target, Errors errors) {
if (target == null) {
return;
}
NewOrderFilesDTO newOrderFilesDTO = (NewOrderFilesDTO) target;
List<MultipartFile> newOrderFiles = newOrderFilesDTO.getFiles();
if (isEmpty(newOrderFiles)) {
return;
}
for (MultipartFile file : newOrderFiles) {
if (!MIME_TYPE_PDF.equals(file.getContentType())) {
errors.rejectValue(file.getName(), file.getName(), "'application/pdf' files allowed only!");
}
if (file.getSize() > ALLOWED_SIZE) {
errors.rejectValue(file.getName(), file.getName(), "File size allowed up to 3MB!");
}
}
}
#Override
public boolean supports(Class<?> cls) {
return NewOrderFilesDTO.class.equals(cls);
}
}
And finally a controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.validation.Valid;
import static org.springframework.http.HttpStatus.NO_CONTENT;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
#Controller
class OrderController {
private final NewOrderFilesValidator newOrderFilesValidator;
#Autowired
OrderController(NewOrderFilesValidator newOrderFilesValidator) {
this.newOrderFilesValidator = newOrderFilesValidator;
}
#InitBinder("newOrderFiles")
void initOrderFilesBinder(WebDataBinder binder) {
binder.addValidators(newOrderFilesValidator);
}
#ResponseStatus(NO_CONTENT)
#RequestMapping(value = ORDERS_PATH, method = POST, consumes = MULTIPART_FORM_DATA_VALUE)
void createOrder(
#Valid #ModelAttribute NewOrderFilesDTO newOrderFiles
) {
}
}
With the configuration above the DTO will be validated automatically by spring.