The @ManyToMany annotation is used to create a many-to-many relationship between the Student and Course entities. The @JoinTable annotation is used to specify the join table that will be used to store the relationship between the two entities. The joinColumns attribute specifies the foreign key column in the join table that refers to the primary key column in the Student entity, and the inverseJoinColumns attribute specifies the foreign key column in the join table that refers to the primary key column in the Course entity.
// create a student Studentstudent=newStudent(); student.setName("John Doe"); studentRepository.save(student);
// another student Studentstudent2=newStudent(); student2.setName("Jane Doe"); studentRepository.save(student2);
// create a javaCourse CoursejavaCourse=newCourse(); javaCourse.setName("Java 101"); courseRepository.save(javaCourse);
// create a pythonCourse CoursepythonCourse=newCourse(); pythonCourse.setName("Python 101"); courseRepository.save(pythonCourse);
// add the student to the javaCourse and pythonCourse javaCourse.getStudents().add(student); pythonCourse.getStudents().add(student); student.getCourses().add(javaCourse); student.getCourses().add(pythonCourse); studentRepository.save(student);
// add the student2 to the javaCourse javaCourse.getStudents().add(student2); student2.getCourses().add(javaCourse); studentRepository.save(student2);
Get a student’s courses
1 2 3 4 5 6 7
studentRepository.findById(1L) .orElseThrow(() -> newRuntimeException("Student Not Found")) .getCourses();
studentRepository.findById(2L) .orElseThrow(() -> newRuntimeException("Student Not Found")) .getCourses();
Unidirectional with @ManyToMany
It is possible to create a unidirectional Many-to-Many relationship as well.
In this case, the Course entity does not have a reference to the Student entity, so the relationship is unidirectional. The join table is still used to store the relationship between the two entities.