In JPA One-To-One mapping, a single instance of one entity is associated with another single instance of another entity.

Basically, a single-valued association is implemented by JPA One-To-One Mapping. For this type of Mapping association, we can only map the source entity to the utmost one instance of the target entity.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

One-To-One Mapping Example

Now let us look at a One-To-One Mapping example where a relationship between an Employee and Office will be demonstrated and the mapping will be implemented in such a way that one employee will be assigned only one project.

For implementing the example, the following steps need to be followed:

  • First under our package called com.JpaOneToOne.mapping, an entity class called Employee.java needs to be created. This entity class will contain the id of the employee or id_of_employee and the name of the employee or name_of_employee.

Now let us check out the code for Employee.java.

package com.jpaOneToOne.mapping;  

import javax.persistence.*;   

@Entity  

public class Employee {  

    @Id  

    @GeneratedValue(strategy=GenerationType.AUTO)  

    private int id_of_employee;  

    private String name_of_employee;  

    public int getId_of_employee() {  

        return id_of_employee;  

    }  

    public void setId_of_employee(int id_of_employee) {  

        this.id_of_employee = id_of_employee;  

    }  

    public String getName_of_employee() {  

        return name_of_employee;  

    }  

    public void setName_of_employee(String name_of_employee) {  

        this.name_of_employee = name_of_employee;  

    }     

}  

  • Next, under the com.JpaOneToOne.mapping package, we need to create another entity class called Office.java. This Office entity class will contain the id of the project or id_of_project, the name of the project or name_of_project, and an object of Employee type with @OneToOne annotation.

Here is the code for Office.java.

package com.jpaOneToOne.mapping;  

import javax.persistence.*;  

@Entity  

public class Office {  

    @Id  

    @GeneratedValue(strategy=GenerationType.AUTO)  

private int id_of_project;  

private String name_of_project;  

@OneToOne  

private Employee emp;  

public Office(int id_of_project, String name_of_project, Employee emp) {  

    super();  

    this.id_of_project = id_of_project;  

    this.name_of_project = name_of_project;  

    this.emp = emp;  

}  

public Office() {  

    super();     

}  

public int getId_of_project() {  

    return id_of_project;  

}   

public void setId_of_project(int id_of_project) {  

    this.id_of_project = id_of_project;  

}   

public String getName_of_project() {  

    return name_of_project;  

}  

public void setName_of_project(String name_of_project) {  

    this.name_of_project = name_of_project;  

}  

public Employee getEmp() {  

    return emp;  

}  

public void setEmp(Employee emp) {  

    this.emp = emp;  

}       

}  

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

  • Now, we need to go to the Persistence.xml and map the entity class and the other database configuration.

Below is the code for Persistence.xml:

<persistence>  

<persistence-unit name="Project_issued">      

      <class>com.jpaOneToOne.mapping.Employee</class>  

      <class>com.jpaOneToOne.mapping.Office</class>      

     <properties>  

      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>  

         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mapping_db"/>  

         <property name="javax.persistence.jdbc.user" value="root"/>  

         <property name="javax.persistence.jdbc.password" value=""/>  

         <property name="eclipselink.logging.level" value="SEVERE"/>  

         <property name="eclipselink.ddl-generation" value="create-or-extend-tables"/>  

      </properties>       

    </persistence-unit>  

</persistence>  

  • Then, under our package called com.jpaOneToOne.mapping, a persistence class called ExampleOfOneToOne needs to be created for persisting the entity object with data.

Now let us check out the code for ExampleOfOneToOne.java:

  ; 

import javax.persistence.*

import com.jpaOneToOne.mapping.*;  

public class ExampleOfOneToOne {  

    public static void main(String[] args) {          

        EntityManagerFactory emf = Persistence.createEntityManagerFactory( "Project_issued" );  

           EntityManager em = emf.createEntityManager( );  

           em.getTransaction( ).begin( );          

           Employee emp1=new Employee();  

           emp1.setId_of_employee(1);  

           emp1.setName_of_employee("Megha");              

           Employee emp2=new Employee();  

           emp2.setId_of_employee(2);  

           emp2.setName_of_employee("Riddhi");              

           em.persist(emp1);  

           em.persist(emp2);               

           Office off1=new Office();  

           off1.setId_of_project(101);  

           off1.setId_of_project("Open Banking System");  

           off1.setStud(emp1);              

           Office off2=new Office();  

           off2.setId_of_project(102);  

           off2.setId_of_project("Low Code No Code Platform");  

           off2.setStud(emp2);             

           em.persist(off1);  

           em.persist(off2);             

           em.getTransaction().commit();  

           em.close();  

           emf.close();  

    }       

}  

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Output:

Under the MySQL workbench, two tables will be generated after our program gets executed.

1. Employee table- Contains all the Employee details. For fetching the data from the Employee table, we need to run the following query in SQL:

select * from employee

JPA_One_To_One_1.

2. Office table - Mapping between the employee and the office is mainly represented by this office table. For fetching the data from the Office table, we need to run the following query in SQL:

select * from office

JPA_One_To_One_2.

UML or Unified Modeling Technology Diagram: Using a Foreign Key

Let’s go through the foreign key based mapping in the following ER (Entity Relation) diagram:

JPA_One_To_One_3.

In the above diagram, the id_of_employee in the employee table works as the foreign key as off_id_of_employee in the office table. Here, we are assigning each project of Office to different employees of the employee table and this is the reason it is called One-To-One mapping.

Looking to accelerate your career as a skilled Full Stack Web Developer? Leverage Caltech CTME's academic excellence in a unique bootcamp-style Post Graduate Program in Full Stack Web Development. Enroll Now!

Conclusion

In this article, we learned about JPA One-To-One Mapping and maintaining one-to-one association in JPA.

As you know, these days along with data structure and algorithms, your development skill is also tested during hirings. A developer should therefore be closely conversant with all the technologies that are being used in the tech industry. Online courses such as Post Graduate Program in Full Stack Web Development can help you master both the frontend and backend with the different types of technologies and tools. This program will give you the foundation for building full-stack web apps using the Java programming language. You'll begin with the basics of JavaScript and then venture into some of the more advanced concepts like Angular, Spring Boot, Hibernate, JSPs, and MVC. 

You can also start learning today's most in-demand skills for free at Simplilearn by enrolling in the SkillUp course and become an expert in different domains of your choice such as Machine Learning, Artificial Intelligence, business analytics etc.

The SkillUp learning platform offers more than 600+ job-ready skills online through 1000+ hours of video lessons. Every time you complete a free program, you can also earn a course completion certificate that serves as a credential for your newly acquired skills. Enroll today!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors