Hackforge Academy

Category: spring_boot

Many-to-Many relationship

Published on 26 Jun 2026

Explanation

A Many-to-Many relationship exists when multiple records from one entity can be associated with multiple records from another entity. For example, a Student can enroll in many Courses, and a Course can have many Students.

Code:

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy =
 GenerationType.IDENTITY)
    private Long id;

    private String name;
}

Explanation

The owning side of a Many-to-Many relationship uses the @ManyToMany annotation along with @JoinTable to define the intermediate mapping table. @Entity public class Student { }

Code:

@Id
    @GeneratedValue(strategy = 
GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(
        name = "student_course",
        joinColumns = 
@JoinColumn(name = "student_id"),
        inverseJoinColumns = 
@JoinColumn(name = "course_id")
    )
    private List<Course> courses;
}

Explanation

The inverse side of the relationship uses the mappedBy attribute to indicate that the relationship is managed by the owning entity.

Code:

@Entity
public class Course {

    @Id
    @GeneratedValue(strategy =
 GenerationType.IDENTITY)
    private Long id;

    private String title;

    @ManyToMany(mappedBy = "courses")
    private List<Student> students;
}

Explanation

Repository interfaces provide CRUD operations for both entities. Spring Data JPA automatically generates the required database queries.

Code:

public interface StudentRepository
 extends JpaRepository<Student, Long> {
}

public interface CourseRepository 
extends JpaRepository<Course, Long> {
}

Explanation

A REST API can associate a student with a course by retrieving both entities, updating the relationship collection, and saving the owning entity. @PostMapping( "/students/{studentId}/courses/{courseId}") public String enrollStudent( @PathVariable Long studentId, @PathVariable Long courseId) { }

Code:

Student student = 
studentRepository.findById(studentId).
orElseThrow();
    Course course = 
courseRepository.findById(courseId).
orElseThrow();

    student.getCourses().add(course);
    studentRepository.save(student);

    return "Student enrolled successfully";

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community