Skip to content

Instantly share code, notes, and snippets.

@pteacher
Created February 21, 2023 09:43
Show Gist options
  • Save pteacher/aa913d8b108bfb2fb85dc2d7ccda4e8c to your computer and use it in GitHub Desktop.
Save pteacher/aa913d8b108bfb2fb85dc2d7ccda4e8c to your computer and use it in GitHub Desktop.
Lecture example with REST API on students Spring Boot JPA
package kg.edu.alatoo.demo.controller;
import kg.edu.alatoo.demo.model.Student;
import kg.edu.alatoo.demo.repository.StudentRepository;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class StudentController {
// CRUD
// POST, GET, PUT, DELETE
private final StudentRepository studentRepository;
public StudentController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@PostMapping("/students")
Student newStudent(@RequestBody Student student) {
return studentRepository.save(student);
}
@GetMapping("/students")
List<Student> getAllStudents() {
return (List) studentRepository.findAll();
}
@GetMapping("/students/{id}")
Optional<Student> getOneStudent(@PathVariable Long id) {
return studentRepository.findById(id);
}
@PutMapping("/students/{id}")
Student updateStudent(@RequestBody Student newStudent, @PathVariable Long id) {
return studentRepository.findById(id).map(
student -> {
student.setName(newStudent.getName());
student.setGpa(newStudent.getGpa());
return studentRepository.save(student);
}).orElseGet(() -> {
newStudent.setId(id);
return studentRepository.save(newStudent);
}
);
}
@DeleteMapping("/student/{id}")
void deleteStudent(@PathVariable Long id) {
studentRepository.deleteById(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment