Spring Boot Microservices Many to Many Relationship Scenario

In this blog post, we will discuss how to use many-to-many relationships in Spring boot microservices projects with simple code snippets.

In a Spring Boot microservices project, when dealing with a relationship like students to courses (and vice versa), you are essentially handling a many-to-many relationship. This can be a bit complex in a microservices architecture compared to a monolithic application due to the distributed nature of data.

Microservices Approach 

Separate Microservices: Ideally, you would have separate microservices for handling students and courses. Each microservice manages its own data and logic. 

Handling Relationships: To maintain the relationship between students and courses, you can use a couple of approaches: 

  • Shared Database: Both microservices access a shared database where the relationship is maintained. This is simpler but goes against the principle of microservices having their own database. 
  • Database per Service: Each microservice has its own database. The relationship is managed through cross-service communication. In this example, we will use this approach.

API Communication: Services communicate with each other via RESTful APIs or asynchronous messaging (like Kafka or RabbitMQ) to handle operations that involve both students and courses. In this example, we use RestTemplate but, you can use WebClient or Open Fiegn library.

Spring Boot Microservices Communication Example using RestTemplate

Spring Boot Microservices Communication Example using WebClient

Spring Boot Microservices Communication Example using Spring Cloud Open Feign

Example Scenario 

Let's consider a simple example with RESTful communication: 

Student Service: Manages student information. 

Course Service: Manages course information. 

Enrollment Service (optional): Manages the association between students and courses.

This source code in this blog post provides a foundational understanding of handling a many-to-many relationship in a microservices architecture using Spring Boot.

Considerations

This example assumes each service has its own database. The Enrollment entity only stores the IDs of students and courses. 

RestTemplate is used for simplicity, but in a real-world scenario, Feign clients or WebClient or a resilient communication mechanism like Resilience4j should be considered. 

Exception handling, transaction management, and service discovery (like Eureka) are important in a real-world scenario but are omitted here for brevity. Ensure the services are correctly registered and discoverable in your microservices environment.

1. StudentService

This service manages the Student infirmation.

Student Entity:

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters and setters
}

Student Controller:

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentRepository repository;

    // Get a student by ID
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudent(@PathVariable Long id) {
        Optional<Student> student = repository.findById(id);
        return student.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // other CRUD methods
}

2. CourseService 

This service manages course information. 

Course Entity:

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    // getters and setters
}

Course Controller:

@RestController
@RequestMapping("/courses")
public class CourseController {
    @Autowired
    private CourseRepository repository;

    // Get a course by ID
    @GetMapping("/{id}")
    public ResponseEntity<Course> getCourse(@PathVariable Long id) {
        Optional<Course> course = repository.findById(id);
        return course.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    // other CRUD methods
}

3. EnrollmentService 

This service manages the association between students and courses. 

Enrollment Entity:

@Entity
public class Enrollment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long studentId;
    private Long courseId;
    // getters and setters
}

Enrollment Controller:

@RestController
@RequestMapping("/enrollments")
public class EnrollmentController {
    @Autowired
    private EnrollmentRepository repository;

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping
    public ResponseEntity<Enrollment> enrollStudent(@RequestBody Enrollment enrollment) {
        // Validate student and course existence
        if (isValidStudent(enrollment.getStudentId()) && isValidCourse(enrollment.getCourseId())) {
            return ResponseEntity.ok(repository.save(enrollment));
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
    }

    private boolean isValidStudent(Long studentId) {
        return restTemplate.getForEntity("http://student-service/students/" + studentId, Student.class).getStatusCode() == HttpStatus.OK;
    }

    private boolean isValidCourse(Long courseId) {
        return restTemplate.getForEntity("http://course-service/courses/" + courseId, Course.class).getStatusCode() == HttpStatus.OK;
    }

    // other methods
}

You can also use WebClient to make a REST API call.

Explanation

StudentService and CourseService: These services manage their respective entities and expose endpoints to retrieve specific students or courses. 

EnrollmentService: It handles the association between students and courses. When enrolling a student, it first validates the existence of the student and the course by calling the respective services. If both are valid, it proceeds to create an enrollment record.

Communication Flow

Enrolling a Student in a Course: 
  • The client sends a request to the Enrollment Service to enroll a student in a course.
  • The Enrollment Service then communicates with both the Student and Course services to validate the existence of the student and the course.
  • Upon validation, the Enrollment Service creates an enrollment record.
Retrieving Course Students: 
  • A request is sent to the Course Service to get students enrolled in a course.
  • The Course Service communicates with the Enrollment Service to get the list of student IDs.
  • It then calls the Student Service to retrieve student details.
Handling Transactions and Consistency:
Implement compensating transactions or use a distributed transaction pattern to handle inconsistencies in a distributed environment.

Related Spring Boot Microservice Tutorials


Comments