JPA One-To-Many Mapping
The One-To-Many mapping comes into the category of collection-valued association where an entity is associated with a collection of other entities. Hence, in this type of association the instance of one entity can be mapped with any number of instances of another entity.
In this example, we will create a One-To-Many relationship between a Student and Library in such a way that one student can be issued more than one type of book.
This example contains the following steps: -
- Create an entity class Student.java under com.javatpoint.mapping package that contains student id (s_id), student name (s_name) with @OneToMany 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).
- Now, map the entity class and other databases confiuguration in Persistence.xml file.
- Create a persistence class OneToManyExample under com.javatpoint.OneToOne 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 book details. To fetch data, run select * from library query in MySQL.
- Student_library table - This table represents the mapping between student and library table. To fetch data, run select * from student_library query in MySQL.