InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
Many-to-Many Relationship in Spring JPA/Hibernate
Suppose there are two entities:
· Student
· Course
You need to implement a many-to-many relationship between them.
Many-to-Many Relationship in Spring JPA/Hibernate (Student & Course)
A many-to-many relationship means that a student can enroll in multiple courses, and each course can have multiple students.
Step-by-Step Simple Implementation:
1. Student Entity
@Entity
public class Student {
@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 Set<Course> courses = new HashSet<>();
}
2. Course Entity
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(mappedBy = "courses")
private Set<Student> students = new HashSet<>();
}
Key Points to Remember
1: Use @ManyToMany annotation in both entities.
2: Use @JoinTable in one entity to define the join table (here, in Student).
3: Use mappedBy in the other entity (here, in Course) to make it bidirectional.
4: The join table (e.g., student_course) links both entities using their IDs.
Summary
This setup allows you to easily add/remove courses for students and vice versa. Spring JPA/Hibernate will automatically manage the join table for you.
This is the easiest way to implement a many-to-many relationship in Spring JPA/Hibernate!