JPA One-To-One Mapping
The One-To-One mapping represents a single-valued association where an instance of one entity is associated with an instance of another entity. In this type of association one instance of source entity can be mapped atmost one instance of target entity.
In this example, we will create a One-To-One relationship between a Student and Library in such a way that one student can be issued only 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) and student name (s_name).
- Create another entity class Library.java under com.javatpoint.mapping package that contains book id (b_id), book name (b_name) and an object of student type marked with @OneToOne annotation.
- Now, map the entity class and other databases confiuguration in Persistence.xml file.
- Create a persistence class OneToOneExample under com.javatpoint.OneToOne package to persist the entity object with data.
After the execution of the program, two 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 represents the mapping between student and library. To fetch data, run select * from library query in MySQL.