Saturday, March 9, 2024

Example Spring boot RESTful controller/ Service/ Spring Data JPA repository/ JPA Entity

Example Spring boot RESTful controller-Service-Spring Data JPA repository-JPA Entity 


The class diagram illustrates the relationships between the entities in the Spring Boot application:



In this diagram:

- `StudentController` is the RESTful controller that handles HTTP requests related to students.

- `StudentService` is a service class that encapsulates business logic. It interacts with the `StudentRepository`.

- `StudentRepository` is a Spring Data JPA repository responsible for database access operations.

- `Student` is the JPA entity representing the data model.


Arrows indicate the relationships between the classes:


- `StudentController` uses `StudentService`.

- `StudentService` uses `StudentRepository`.

- `StudentRepository` uses `Student` entity.


This hierarchical structure represents the flow of responsibility and data in the Spring Boot application. The controller handles incoming requests, the service layer contains business logic, and the repository manages database interactions, all centered around the `Student` entity.

Spring Boot application with a Student entity, a JpaRepository for data access, a service layer, and a RESTful controller to handle requests related to students.

1. Student Entity

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;


@Entity

public class Student {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    private String firstName;

    private String lastName;

    private int age;


    // Constructors, getters, and setters

}

2. Student Repository (DAO using Spring Data JPA)

import org.springframework.data.jpa.repository.JpaRepository;


public interface StudentRepository extends JpaRepository<Student, Long> {

    // Custom queries can be added here if needed

}

3. Student Service

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


import java.util.List;


@Service

public class StudentService {


    private final StudentRepository studentRepository;


    @Autowired

    public StudentService(StudentRepository studentRepository) {

        this.studentRepository = studentRepository;

    }


    public List<Student> getAllStudents() {

        return studentRepository.findAll();

    }


    public Student getStudentById(Long id) {

        return studentRepository.findById(id).orElse(null);

    }


    public void saveStudent(Student student) {

        studentRepository.save(student);

    }


    public void deleteStudent(Long id) {

        studentRepository.deleteById(id);

    }

}

4. Student Controller

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.List;


@RestController

@RequestMapping("/api/students")

public class StudentController {


    private final StudentService studentService;


    @Autowired

    public StudentController(StudentService studentService) {

        this.studentService = studentService;

    }


    @GetMapping

    public List<Student> getAllStudents() {

        return studentService.getAllStudents();

    }


    @GetMapping("/{id}")

    public Student getStudentById(@PathVariable Long id) {

        return studentService.getStudentById(id);

    }


    @PostMapping

    public void saveStudent(@RequestBody Student student) {

        studentService.saveStudent(student);

    }


    @DeleteMapping("/{id}")

    public void deleteStudent(@PathVariable Long id) {

        studentService.deleteStudent(id);

    }

}

5. Spring Boot Application

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class SpringBootStudentApplication {


    public static void main(String[] args) {

        SpringApplication.run(SpringBootStudentApplication.class, args);

    }

}


Ensure that you have the necessary dependencies in your `pom.xml` or `build.gradle` file for Spring Boot, Spring Data JPA, and an embedded database (e.g., H2 for simplicity in this example).


With these components, you have a basic Spring Boot application with a RESTful API for managing student entities. The `StudentController` handles HTTP requests, the `StudentService` encapsulates business logic, and the `StudentRepository` provides data access through Spring Data JPA. The application uses an in-memory H2 database by default, but you can configure it to use a different database based on your requirements.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...