Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
In Java, many-to-many relationships between entities can be modeled using appropriate data structures and object-oriented principles. In this example, we will model a many-to-many relationship between Student
and Course
entities. A student can enroll in multiple courses, and a course can be taken by multiple students.
Student
class:import java.util.HashSet; import java.util.Set; public class Student { private int id; private String name; private Set<Course> courses; public Student(int id, String name) { this.id = id; this.name = name; this.courses = new HashSet<>(); } // Getters and setters public void enroll(Course course) { courses.add(course); course.addStudent(this); } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
Course
class:import java.util.HashSet; import java.util.Set; public class Course { private int id; private String title; private Set<Student> students; public Course(int id, String title) { this.id = id; this.title = title; this.students = new HashSet<>(); } // Getters and setters public void addStudent(Student student) { students.add(student); } @Override public String toString() { return "Course{" + "id=" + id + ", title='" + title + '\'' + '}'; } }
Create a test class to demonstrate the many-to-many relationship between Student
and Course
.
public class Main { public static void main(String[] args) { // Create students Student alice = new Student(1, "Alice"); Student bob = new Student(2, "Bob"); // Create courses Course math = new Course(101, "Math"); Course history = new Course(102, "History"); // Enroll students in courses alice.enroll(math); alice.enroll(history); bob.enroll(math); // Print enrolled students in courses System.out.println("Students enrolled in Math:"); for (Student student : math.getStudents()) { System.out.println(student); } System.out.println("Students enrolled in History:"); for (Student student : history.getStudents()) { System.out.println(student); } // Print courses a student is enrolled in System.out.println("Courses Alice is enrolled in:"); for (Course course : alice.getCourses()) { System.out.println(course); } } }
This example demonstrates a simple many-to-many relationship between Student
and Course
entities in Java. You can extend this model to include more features or properties as needed, such as adding methods to remove students from courses or adding a registration date to the relationship.
Using JPA for many-to-many mapping in Java:
@Entity public class Student { @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) private Set<Course> courses; // Other fields and methods }
Hibernate many-to-many relationship example in Java:
@Entity public class Student { @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) private Set<Course> courses; // Other fields and methods }
Java Spring many-to-many relationship example:
@Entity public class Student { @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) private Set<Course> courses; // Other fields and methods }
Database schema design for many-to-many relationships in Java:
CREATE TABLE student ( student_id INT PRIMARY KEY, -- other fields ); CREATE TABLE course ( course_id INT PRIMARY KEY, -- other fields ); CREATE TABLE student_course ( student_id INT, course_id INT, PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES student(student_id), FOREIGN KEY (course_id) REFERENCES course(course_id) );
Fetching and persisting many-to-many relationships in Java:
// Fetching example Student student = entityManager.find(Student.class, 1); Set<Course> courses = student.getCourses(); // Persisting example Student student = new Student(); Course course = new Course(); student.addCourse(course); entityManager.persist(student);
Handling cascading operations in many-to-many relationships:
Student
is deleted, you might want to delete associated Courses
as well.@ManyToMany(cascade = CascadeType.ALL)
Bidirectional vs. unidirectional many-to-many relationships in Java:
// Bidirectional class Student { @ManyToMany(mappedBy = "students") private Set<Course> courses; } class Course { @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "course_id"), inverseJoinColumns = @JoinColumn(name = "student_id")) private Set<Student> students; }