In this article, i am going to discuss how to map many to many relationship using @ManyToMany annotation available in JPA (Java Persistence Api).
Lets look at the following ER-Diagram.
This ER-Diagram describes the relationship between Students and Courses. According to the diagram, the relationship can be described as below.
- A student can enroll for many courses.
- A course can be enrolled by many students.
Therefore the relationship between Students and Courses is many to many.
If we convert this relationship into relational database model, the table structure should looks like below.
Lets implement this relationship with Spring Data JPA Project. The full source code of this article can be found at GitHub.
Here is the Student class.
In Student class we are going the map the relationship from Student to Course. As you are already aware, it is a many to many relationship and there should be an intermediate table (joined table) to map the relationship. Therefore we have used the @JoinTable annotation to define the joined/intermediate table with its properties.
The name of the joined table (newly created intermediate table) will be “student_courses” as declared. In addition, there will be two join columns.
- student_id – This will refer the “id” column of the “students” table.
- course_id – This will refer the “id” column of the “courses” table.
Here is the Course class.
In Course class, we just declare only the relationship from Course to Student. Since the relationship is many to many, it is just declared with @ManyToMany annotation. We are not going to map the relationship as it is already mapped by Student class and it is denoted with mappedBy attribute.
What is “mappedBy” attribute here?
mappedBy attributes defines the owner of the relationship. As you can see that relationship has been defined and owned by the courses property of the Student class. Therefore in the Course class it is declared with mappedBy=”courses”.
This will tells that the relationship has been mapped and owned by the courses property of the Student class.
Run and Test the source code.
You can get the source code related to this project from GitHub (Click here). Please change the database configuration in application.properties based on your development environment. The run the following command to build the project.
After executing the above command successfully, the table structure will be created with all defined properties.
Here you can see that the joined table contains only the foreign key for reference entities/tables. we have not added any extra column for the joined table.