JPA Many-To-One Mapping
The Many-To-One mapping represents a single-valued association where a collection of entities can be associated with the similar entity. Hence, in relational database any more than one row of an entity can refer to the similar rows of another entity.
In this example, we will create a Many-To-One relationship between a Student and Library in such a way that more than one student can issued the same book.
This example contains the following steps: –
- Create an entity class Student.java under com.tutoraspire.mapping package that contains student id (s_id) and student name (s_name) with @ManyToOne annotation that contains an object of Library type.
- Create another entity class Library.java under com.tutoraspire.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 ManyToOneExample under com.tutoraspire.ManyToOne package to persist the entity object with data.
After the execution of the program, the two tables generates under MySQL workbench.
- Library table – This table contains the library details. To fetch data, run select * from library query in MySQL.
- Student table – This table represents the mapping between student and library. To fetch data, run select * from student query in MySQL.