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";