I have tried to delete a row from database using Spring data deleteById method but it returns null.
ProductServiceImpl
public void removeOne(Long id) {
Product product = findById(id);
productRepository.deleteById(product);
ProductRepository
public interface ProductRepository extends CrudRepository<Product, Long> {
void deleteById(Product product);
Controller
#RequestMapping(value="/remove", method=RequestMethod.POST)
public String remove(#ModelAttribute("id") String id, Model model) {
productService.removeOne(Long.parseLong(id.substring(10)));
List<Product> productList = productService.findAll();
model.addAttribute("productList", productList);
System.out.println("deleted successfully !!!!");
return "redirect:/product/productList";
}
Why you write it complex. Some code not necessary .First, you extends CrudRepository,it mean you don't need create custom method void deleteById(Product product); because crud contain method deleteById.
Second, Controller why you using : #RequestMapping(value="/remove", method=RequestMethod.POST) . I think it must : #DeleteMapping("/remove") . And in controller only call.
#Autowired
private ProductRepository productRepository;
#DeleteMapping("/remove/{id}")
public String remove(#PathVariable String id) {
productRepository.deleteById(id);
return "redirect:/product/productList";
}
#Autowired
private ProductRepository productRepository;
#RequestMapping(value="/remove", method=RequestMethod.POST)
public String remove(#RequestParam String id) {
productRepository.deleteById(id);
return "redirect:/product/productList";
}
Related
I have an issue while mapping the DTO to Entity the CVV and expiration date not working but the number of the card is working fine, and mapping the did I miss any configuration ??
I have class A inherit from PaymentRequestDTO and class B inherit PaymentRequest
and mapping using this.modelmapper().map(classA, classB);
Parent Class for A
public abstract class PaymentRequestDTO {
....
CardRequestDTO card;
...
}
CardDTO
public class CardRequestDTO {
#JsonProperty("name")
public String name;
#JsonProperty("number")
public String number;
#JsonProperty("expiryMonth")
public String expiryMonth;
#JsonProperty("expiryYear")
public String expiryYear;
#JsonProperty("cvv")
public String cvv;
}
Parent Class for B
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public abstract class PaymentRequest{
#JsonProperty("card_number")
public String cardNumber;
#JsonProperty("expiry_date")
public String expiryDate;
#JsonProperty("card_security_code")
public String cardSecurityCode;
}
PropertyMap class
public class PaymentRequestConverter extends PropertyMap<PaymentRequestDTO, PaymentRequest> {
#Override
protected void configure() {
map().setCardNumber(source.getCard().getNumber());
map().setCardSecurityCode(source.getCard().getCvv());
map().setExpiryDate(FortHelper.expiryDate(source.getCard().getExpiryYear(), source.getCard().getExpiryMonth()));
}
}
Here is my model mapper
#Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.createTypeMap(PaymentRequestDTO.class, PaymentRequest.class).addMappings(new PaymentRequestConverter());
return modelMapper;
}
Model mapper version 3.1.0
I have a simple document:
#Document
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString
public class ProductUnit {
#Id
String id;
private String name;
private Integer price;
private LocalDateTime localDateTime;
}
Simple MongoRepository :
public interface productRepo extends MongoRepository<ProductUnit,String> {
ProductUnit deleteByName(String name);
List<ProductUnit> findByPrice(Integer price);
}
and Service :
#Service
public class productServiseImpl implements productServise {
#Autowired
productRepo repository;
#Override
public ProductUnit saveOrUpdate(ProductUnit productUnit) {
System.out.println("inside save or update");
return repository.save(productUnit);
}
#Override
public List<ProductUnit> findAll() {
return repository.findAll();
}
#Override
public ProductUnit deleteUnitByPrice(String name) {
return repository.deleteByName(name);
}
#Override
public List<ProductUnit> findByPrice(Integer price) {
return repository.findByPrice(price);
}
}
Now , inside RestController , I pass id through a post request and use a random class to generate a random value of the price and name .At this stage everything is fine, i.e. all values were initialized correctly, but when it comes to service.saveOrUpdate(forSave) It stores the value incorrectly, i.e. the request returns an empty json and the findAll method returns a list of empty json.Can you tell me what the error is? thanks
#RestController
public class productUnitRestController {
#Autowired
productServise service;
#Autowired
Supplier<MetaInfGenerator> generatorSupplier;
#GetMapping(path = "/all")
public List<ProductUnit> getAllProoduct(){
return service.findAll();
}
#PostMapping(path = "/products")
public ProductUnit createProoduct(#RequestParam("id") Optional<String> newId){
System.out.println("***** iside PostMapping ******");
MetaInfGenerator generator = generatorSupplier.get();
System.out.println("***** supplier PostMapping ******");
ProductUnit forSave = ProductUnit.builder()
.id(newId.get())
.name(generator.getRandomString())
.price(generator.getRandomInteger())
.localDateTime(LocalDateTime.now()).build();
System.out.println(forSave);
return service.saveOrUpdate(forSave);
}
}
I have a spring-boot application and I use DTO like that:
Service
#Service
public class UnitOfMeasureServiceImpl implements IUnitOfMeasureService {
private final IUnitsOfMeasureRepository unitOfMeasureRepository;
#Autowired
public UnitOfMeasureServiceImpl(IUnitsOfMeasureRepository unitOfMeasureRepository) {
this.unitOfMeasureRepository = unitOfMeasureRepository;
}
#Override
public UnitOfMeasureDTO getUnitOfMeasureById(UUID id) {
Optional<UnitOfMeasure> optionalUnitOfMeasure = unitOfMeasureRepository.findById(id);
if (!optionalUnitOfMeasure.isPresent()){
// throw new ComponentNotFoundException(id);
return null;
}
return UnitOfMeasureDTO.factory(optionalUnitOfMeasure.get());
}
dto:
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class UnitOfMeasureDTO {
private String id;
private String name;
private String description;
private String sourceInfoCompanyName;
private String originalId;
public static UnitOfMeasureDTO factory(UnitOfMeasure unitOfMeasure) {
UnitOfMeasureDTO dto = new UnitOfMeasureDTO();
dto.id = unitOfMeasure.getId().toString();
dto.name = unitOfMeasure.getName();
dto.description = unitOfMeasure.getDescription();
dto.sourceInfoCompanyName = unitOfMeasure.getSourceInfo().getSourceCompany().getName();
dto.originalId = unitOfMeasure.getOriginalId();
return dto;
}
}
controller:
#RestController
#RequestMapping(UnitOfMeasureController.BASE_URL)
public class UnitOfMeasureController {
public static final String BASE_URL = "/api/sust/v1/unitOfMeasures";
private final IUnitOfMeasureService unitOfMeasureService;
public UnitOfMeasureController(IUnitOfMeasureService unitOfMeasureService) {
this.unitOfMeasureService = unitOfMeasureService;
}
#GetMapping(path = "/{id}")
#ResponseStatus(HttpStatus.OK)
public UnitOfMeasureDTO getUnitOfMeasureDTO(#PathVariable("id") UUID id) {
UnitOfMeasureDTO unitOfMeasureDTO = unitOfMeasureService.getUnitOfMeasureById(id);
return unitOfMeasureDTO;
}
So in my service I have getUnitOfMeasureById(UUID id) that return a UnitOfMeasureDTO.
Now I need to call, from another service, getUnitOfMeasureById(UUID id) that return the domain entity UnitOfMeasure. I think it's correct to call a service method from another service (not a controller method!) and the separation between business logic is at the service layer. So is it correct to have 2 methods: getUnitOfMeasureDTOById and getUnitOfMeasureById in the service? (getUnitOfMeasureDTOById call getUnitOfMeasureById to avoid code duplication)
Say, in request, I'm getting
?name=Jack&age=26&price=100&quantity=2
I have two model objects as below
public class User {
public String name;
public String age;
//getters and setters
}
public class Order {
public int price;
public int quantity;
//getters and setters
}
Now I want to have a controller method as below
#RequestMapping(value = "/submit", method = RequestMethod.GET)
public String home(#ModelAttribute("user") User user, #ModelAttribute("order") Order order, Model model) {
//stuff
}
As you can see I want to populate the model objects using two separate #ModelAttribute annotation. Is this possible in spring mvc?
Sattyaki, I suggest you to provide a few getters/setters to User and Order, and then compose the desired request with another class:
public class Checkout {
private User user;
private Order order;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
And to request for this operation, just issue a GET to the wanted URI(/submit) with your parameters. Observe that they are now using dot notation:
/submit?user.name=Jack&user.age=26&order.price=100&order.quantity=2
I have two entity class.one is PhaseEntity and another is TaskEntity. PhaseId will be the foreign key of TaskEntity class. I can create and save the value to the database but cannot update the database.
Portion of TaskEntity class:
#ManyToOne(optional=false)
#JoinColumn(name="phaseId")
private PhaseEntity phaseEntity;
Controller class:
public class TaskController {
#Autowired
private TaskService taskService;
#Autowired
private PhaseService phaseService;
#RequestMapping(value="/task/create",method=RequestMethod.GET)
public String createForm(Model model,Principal principal){
model.addAttribute(new TaskEntity());
model.addAttribute("body", "task/task-create");
model.addAttribute("generaltaskDto",new GeneralTaskDto());
model.addAttribute("phaseEntities", phaseService.phaseList());
return "layouts/default";
}
#RequestMapping(value="/task/create",method=RequestMethod.POST)
public String createFormPost(Model model,GeneralTaskDto generaltaskDto,BindingResult result){
TaskEntity taskAndPhase=generaltaskDto.getTaskEntity();
taskAndPhase.setPhaseEntity(phaseService.getPhaseByPhaseId(generaltaskDto.getPhaseId()));
taskService.saveTask(taskAndPhase);
return "redirect:/task/list";
}
#GetMapping(value="/task/update/{id}")
public String updateTask(Model model,#PathVariable String id){
TaskEntity taskEntity= taskService.getTaskId(Integer.parseInt(id));
model.addAttribute("body", "task/task-create");
model.addAttribute("phaseEntities", phaseService.phaseList());
return "layouts/default";
}
GeneraltaskDto class:
public class GeneralTaskDto {
private TaskEntity taskEntity=new TaskEntity();
private Integer phaseId;
public TaskEntity getTaskEntity() {
return taskEntity;
}
public void setTaskEntity(TaskEntity taskEntity) {
this.taskEntity = taskEntity;
}
public Integer getPhaseId() {
return phaseId;
}
public void setPhaseId(Integer phaseId) {
this.phaseId = phaseId;
}
}
here is the client page of the application
can anyone help plz how to update the database with controller request. Thanks in advance.
Please try adding these lines in your controller under updateTask method after TaskEntity taskEntity= taskService.getTaskId(Integer.parseInt(id)); line.
PhaseEntity phaseEntity=taskEntity.getPhaseEntity();
generaltaskDto.setTaskEntity(taskEntity);
generaltaskDto.setPhaseId(phaseEntity.getPhaseId());
model.addAttribute("generaltaskDto", generaltaskDto);