Javatpoint Logo
Javatpoint Logo

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.

@ManyToMany Example

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.

Library.java

  • Now, map the entity class and other databases confiuguration in Persistence.xml file.

Persistence.xml

  • Create a persistence class ManyToOneExample under com.javatpoint.ManyToOne package to persist the entity object with data.

Output:

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.

JPA Many-To-Many Mapping
  • Library table - This table contains the library details. To fetch data, run select * from library query in MySQL.

JPA Many-To-Many Mapping
  • Library_student - This table contains the library details. To fetch data, run select * from library_student query in MySQL.

JPA Many-To-Many Mapping




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA