Javatpoint Logo
Javatpoint Logo

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.

@OneToMany Example

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.

Student.java

  • Create another entity class Library.java under com.javatpoint.mapping package that contains book id (b_id), book name (b_name).

Library.java

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

Persistence.xml

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

OneToManyExample.java

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 One-To-Many Mapping
  • Library Table - This table contains the library book details. To fetch data, run select * from library query in MySQL.

JPA One-To-Many Mapping
  • Student_library table - This table represents the mapping between student and library table. To fetch data, run select * from student_library query in MySQL.

JPA One-To-Many Mapping





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA