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);.
Person.java
import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToMany
@JoinTable(
name = "person_course",
joinColumns = @JoinColumn(name = "person_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses = new HashSet<>();
public Person() {}
public Person(String name) {
this.name = name;
}
// Getters & Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set<Course> getCourses() { return courses; }
public void setCourses(Set<Course> courses) { this.courses = courses; }
public void addCourse(Course course) {
courses.add(course);
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.
Course.java
import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToMany(mappedBy = "courses")
private Set<Person> persons = new HashSet<>();
public Course() {}
public Course(String title) {
this.title = title;
}
// Getters & Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
}
Session Create:
Create a separate Hibernate utility class to manage SessionFactory:
HibernateUtil.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
return new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Person.class)
.addAnnotatedClass(Course.class)
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() {
return sessionFactory.openSession(); // Opens a new session when needed
}
public static void shutdown() {
sessionFactory.close(); // Close SessionFactory when the application shuts down
}
}
CRUD Operations in Many-to-Many:
Insert Data (Adding Students and Courses)
- Hibernate automatically inserts records in the
student_coursetable.
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
// Create Courses
Course java = new Course("Java Programming");
Course python = new Course("Python Basics");
// Create Students
Student alice = new Student("Alice");
Student bob = new Student("Bob");
// Enroll Students in Courses
alice.addCourse(java);
alice.addCourse(python);
bob.addCourse(java);
// Save Data
session.persist(java);
session.persist(python);
session.persist(alice);
session.persist(bob);
transaction.commit();
session.close();
}
}
Fetch Data (Get Student and Courses):
Session session = HibernateUtil.getSession();
Person person = session.get(Person.class, 1L);
System.out.println("Person: " + person.getName());
for (Course course : person.getCourses()) {
System.out.println("Enrolled in: " + course.getTitle());
}
session.close();
Output
Student: Alice
Enrolled in: Java Programming
Enrolled in: Python Basics
Update Data (Add Course to Existing Student):
- Automatically updates the
person_coursetable.
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Person person = session.get(Person.class, 1L);
Course course = session.get(Course.class, 3L);
if (person != null && course != null) {
person.addCourse(course);
session.merge(person);
}
transaction.commit();
session.close();
Delete Student (Cascade Deletion):
Session session = HibernateUtil.getSession();
Transaction transaction = session.beginTransaction();
Person person = session.get(Person.class, 1L);
if (person != null) {
session.remove(person);
}
transaction.commit();
session.close();
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 |