Introduction
In this chapter, we will build a Delete Student REST API for our Student Management System Project with a MySQL database. We will update the service layer, build the Delete Student REST API, and test it using the Postman client. Each step will be explained in detail.
What We Will Cover in This Chapter
- Update a Service Layer (interface and implementation class)
- Build Delete Student REST API
- Test using Postman client
- Conclusion
Update a Service Layer
Update the Service Interface
- Open
StudentServiceInterface:- In the
src/main/java/com/example/springbootmysqlcrud/servicedirectory, open theStudentServiceinterface. - Add the following method to the
StudentServiceinterface:
- In the
package com.example.springbootmysqlcrud.service;
import com.example.springbootmysqlcrud.model.Student;
import java.util.List;
import java.util.Optional;
public interface StudentService {
Student saveStudent(Student student);
Optional<Student> getStudentById(Long id);
List<Student> getAllStudents();
Student updateStudent(Long id, Student student);
void deleteStudent(Long id);
}
Explanation
- Service Interface: Defines the contract for the service layer. It now includes the
deleteStudentmethod to delete a student by ID.
Update the Service Implementation Class
- Open
StudentServiceImplClass:- In the
src/main/java/com/example/springbootmysqlcrud/servicedirectory, open theStudentServiceImplclass. - Add the following method to the
StudentServiceImplclass:
- In the
package com.example.springbootmysqlcrud.service;
import com.example.springbootmysqlcrud.model.Student;
import com.example.springbootmysqlcrud.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
@Override
public Optional<Student> getStudentById(Long id) {
return studentRepository.findById(id);
}
@Override
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
@Override
public Student updateStudent(Long id, Student studentDetails) {
return studentRepository.findById(id)
.map(student -> {
student.setFirstName(studentDetails.getFirstName());
student.setLastName(studentDetails.getLastName());
student.setEmail(studentDetails.getEmail());
return studentRepository.save(student);
})
.orElse(null);
}
@Override
public void deleteStudent(Long id) {
studentRepository.deleteById(id);
}
}
Explanation
deleteStudentMethod: Implements thedeleteStudentmethod defined in theStudentServiceinterface to delete a student by ID using the repository.
Build Delete Student REST API
Create or Update the Controller Class
- Open
StudentControllerClass:- In the
src/main/java/com/example/springbootmysqlcrud/controllerdirectory, open theStudentControllerclass. - Add the following method to the
StudentControllerclass:
- In the
package com.example.springbootmysqlcrud.controller;
import com.example.springbootmysqlcrud.model.Student;
import com.example.springbootmysqlcrud.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping
public ResponseEntity<Student> saveStudent(@RequestBody Student student) {
Student savedStudent = studentService.saveStudent(student);
return new ResponseEntity<>(savedStudent, HttpStatus.CREATED);
}
@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
Optional<Student> student = studentService.getStudentById(id);
return student.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
List<Student> students = studentService.getAllStudents();
return new ResponseEntity<>(students, HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student studentDetails) {
Student updatedStudent = studentService.updateStudent(id, studentDetails);
return updatedStudent != null ? new ResponseEntity<>(updatedStudent, HttpStatus.OK)
: new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
Explanation
@DeleteMapping("/{id}"): Handles HTTP DELETE requests to delete a student by ID.@PathVariable: Binds the method parameter to the value of the path variable.ResponseEntity: Wraps the response and sets the HTTP status to204 No Contentfor successful deletion.
Test Using Postman Client
Step-by-Step Testing
-
Open Postman:
- Launch the Postman client from your installed applications.
-
Create a New Request:
- Click on "New" and then select "Request".
-
Set Request Type and URL:
- Set the request type to
DELETE. - Enter the URL:
http://localhost:8080/api/students/{id}(replace{id}with the actual student ID).
- Set the request type to
-
Send Request:
- Click the "Send" button.
- Verify that the response status is
204 No Contentif the student is deleted or404 Not Foundif the student does not exist.
Explanation
- Request Type:
DELETEindicates that we are deleting data. - URL: Points to the Delete Student REST API endpoint with the student ID as a path variable.
- Response: Verifies that the student is deleted or that the appropriate error message is shown.
Conclusion
In this chapter, we built a Delete Student REST API for our Student Management System Project with a MySQL database. We updated the service layer, built the Delete Student REST API, and tested it using the Postman client. Each step was explained in detail. This concludes the CRUD operations for the Student Management System Project.