Implement a spring boot project to create student entity using CRUD Operation
with exception handling.
1. Create Student Entity:
import [Link];
import [Link];
import [Link];
import [Link];
@Entity
public class Student {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String firstName;
private String lastName;
private int age;
// Getters and setters
}
2. Create Student Repository:
import [Link];
public interface StudentRepository extends JpaRepository<Student, Long> {
3. Create Student Service with CRUD Operations and Exception
Handling:
import [Link];
import [Link];
import [Link];
import [Link];
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public List<Student> getAllStudents() {
return [Link]();
public Optional<Student> getStudentById(Long id) {
return [Link](id);
public Student saveStudent(Student student) {
return [Link](student);
public Student updateStudent(Long id, Student updatedStudent) {
if ([Link](id)) {
[Link](id);
return [Link](updatedStudent);
} else {
throw new StudentNotFoundException("Student not found with id: " + id);
public void deleteStudent(Long id) {
if ([Link](id)) {
[Link](id);
} else {
throw new StudentNotFoundException("Student not found with id: " + id);
4. Create Custom Exception Class:
public class StudentNotFoundException extends RuntimeException {
public StudentNotFoundException(String message) {
super(message);
5. Create Student Controller:
java
import [Link];
import [Link].*;
import [Link];
import [Link];
@RestController
@RequestMapping("/api/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public List<Student> getAllStudents() {
return [Link]();
@GetMapping("/{id}")
public Student getStudentById(@PathVariable Long id) {
return [Link](id)
.orElseThrow(() -> new StudentNotFoundException("Student not found
with id: " + id));
}
@PostMapping
public Student saveStudent(@RequestBody Student student) {
return [Link](student);
@PutMapping("/{id}")
public Student updateStudent(@PathVariable Long id, @RequestBody Student
updatedStudent) {
return [Link](id, updatedStudent);
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable Long id) {
[Link](id);
6. Run the Application:
Run the Spring Boot application, and it should start a
server on [Link] by default.
Now you can use tools like Postman or curl to test your
CRUD operations for student management. The
endpoints include:
GET /api/students: Get all students
GET /api/students/{id}: Get a specific student by ID
POST /api/students: Create a new student
PUT /api/students/{id}: Update an existing student
DELETE /api/students/{id}: Delete a student by ID