/* * Last updated: 22/04/2021 */ package com.example.controller; import com.example.exception.ResourceNotFoundException; import com.example.model.Students; import com.example.service.StudentsService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author Tuoi-cm * Student Controller * @version 1.0 */ @RestController @RequestMapping(value = "api/student") public class StudentsController { @Autowired private StudentsService studentsService; // Get All Student @GetMapping(value = "/all") public List listStudents () { return this.studentsService.listAll(); } //Get One Student @GetMapping(value = "/one") public Students oneStudent (@RequestParam("id") Long id) { return this.studentsService.findById(id). orElseThrow(() -> new ResourceNotFoundException("Not Found Student With Id: " + id)); } //Add Student @PostMapping(value = "/add") public Students addStudent(@RequestBody Students student) { return this.studentsService.save(student); } //Update Student @PutMapping(value = "edit") public Students editStudents(@RequestParam("id") Long id, @RequestBody Students editStudent) { Students student = this.studentsService.findById(id). orElseThrow(() -> new ResourceNotFoundException("Not Found Student With Id: " + id)); student.setFullName(editStudent.getFullName()); student.setAge(editStudent.getAge()); return this.studentsService.save(student); } //Delete Student @DeleteMapping(value = "delete") public String deleteStudent(@RequestParam("id") Long id) { Students student = this.studentsService.findById(id). orElseThrow(() -> new ResourceNotFoundException("Not Found Student With Id: " + id)); this.studentsService.delete(id); return "Deleted Student with Full-Name: " + student.getFullName(); } }