From a8c51163ea680889bb69f712fa110bbda7fce066 Mon Sep 17 00:00:00 2001 From: Zak Date: Tue, 11 Jan 2022 23:49:01 +0100 Subject: [PATCH] Update StudentController.java 1- Why not using @Autowired ? 2- Spring Data JPA has the save() method which does both inserting and updating depending on the context; if the entity has the id(primary_key), then it will perform an update, otherwise it will save it as a new item. --- .../sms/controller/StudentController.java | 23 +------------------ 1 file changed, 1 insertion(+), 22 deletions(-) diff --git a/src/main/java/net/javaguides/sms/controller/StudentController.java b/src/main/java/net/javaguides/sms/controller/StudentController.java index a0e56d3..c6e9f86 100644 --- a/src/main/java/net/javaguides/sms/controller/StudentController.java +++ b/src/main/java/net/javaguides/sms/controller/StudentController.java @@ -13,12 +13,8 @@ @Controller public class StudentController { + @Autowired private StudentService studentService; - - public StudentController(StudentService studentService) { - super(); - this.studentService = studentService; - } // handler method to handle list students and return mode and view @GetMapping("/students") @@ -48,23 +44,6 @@ public String editStudentForm(@PathVariable Long id, Model model) { model.addAttribute("student", studentService.getStudentById(id)); return "edit_student"; } - - @PostMapping("/students/{id}") - public String updateStudent(@PathVariable Long id, - @ModelAttribute("student") Student student, - Model model) { - - // get student from database by id - Student existingStudent = studentService.getStudentById(id); - existingStudent.setId(id); - existingStudent.setFirstName(student.getFirstName()); - existingStudent.setLastName(student.getLastName()); - existingStudent.setEmail(student.getEmail()); - - // save updated student object - studentService.updateStudent(existingStudent); - return "redirect:/students"; - } // handler method to handle delete student request