Advertisement
Google Ad Slot: content-top
Hibernate Many-to-Many Mapping
A Many-to-Many relationship exists when multiple records in one table are associated with multiple records in another table.
For example:
- A Student can enroll in multiple Courses.
- A Course can have multiple Students.
✅ This requires a Join Table to link the two entities.
StudentEntity (Many-to-Many withCourse)CourseEntity (Many-to-Many withStudent)- Join Table (
student_course) for mapping.
Person Entity:
@ManyToMany→ A student can enroll in many courses.@JoinTable→ Defines the join tableperson_course.- Bidirectional Relationship → We add
course.getPersons().add(this);.
Course Entity:
mappedBy = "courses"→ This refers to the courses field in theStudententity.- Bidirectional Relationship → A course also maintains a list of students.
Session Create:
Create a separate Hibernate utility class to manage SessionFactory:
CRUD Operations in Many-to-Many:
Insert Data (Adding Students and Courses)
- Hibernate automatically inserts records in the
student_coursetable.
Fetch Data (Get Student and Courses):
Update Data (Add Course to Existing Student):
- Automatically updates the
person_coursetable.
Delete Student (Cascade Deletion):
Database Table Structure:
Table name : person
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
Table name : course
| id | title |
|---|---|
| 1 | Java Programming |
| 2 | Python Programming |
Join Table: student_course
| student_id | course_id |
|---|---|
| 1 | 2 |
| 1 | 2 |
| 2 | 1 |