Home » JPA One-To-One Mapping

JPA One-To-One Mapping

by Online Tutorials Library

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.

@OneToOne Example

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.tutoraspire.mapping package that contains student id (s_id) and student name (s_name).

Student.java

  • Create another entity class Library.java under com.tutoraspire.mapping package that contains book id (b_id), book name (b_name) and an object of student type marked with @OneToOne annotation.

Library.java

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

Persistence.xml

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

OneToOneExample.java

Output:

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.

JPA One-To-One Mapping

  • Library table – This table represents the mapping between student and library. To fetch data, run select * from library query in MySQL.

JPA One-To-One Mapping

You may also like