JPA Many-To-Many Mapping
The Many-To-Many mapping represents a collection-valued association where any number of entities can be associated with a collection of other entities. In relational database any number of rows of one entity can be referred to any number of rows of another entity.
In this example, we will create a Many-To-Many relationship between a Student and Library in such a way that any number of students can be issued any type of books.
This example contains the following steps: -
- Create an entity class Student.java under com.javatpoint.mapping package that contains student id (s_id) and student name (s_name) with @ManyToMany annotation that contains Library class object of List type.
- Create another entity class Library.java under com.javatpoint.mapping package that contains book id (b_id), book name (b_name) with @ManyToMany annotation that contains Student class object of List type.
- Now, map the entity class and other databases confiuguration in Persistence.xml file.
- Create a persistence class ManyToOneExample under com.javatpoint.ManyToOne package to persist the entity object with data.
After the execution of the program, three tables are generated under MySQL workbench.
- Student table - This table contains the student details. To fetch data, run select * from student query in MySQL.
- Library table - This table contains the library details. To fetch data, run select * from library query in MySQL.
- Library_student - This table contains the library details. To fetch data, run select * from library_student query in MySQL.