Table of contents
1.
Introduction
2.
Persistent Classes For One-to-One Mapping
3.
Modifying pom.xml File
4.
Configuration File
5.
Classes To Store And Fetch Data
6.
Frequently Asked Questions
6.1.
What are the advantages of Hibernate Framework?
6.2.
What is a Persistent Entity?
6.3.
What are the four layers of Hibernate architecture? 
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

One To One Annotation

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hibernate supports one-to-one mapping by using annotation on one-to-one elements. No foreign key is created in the primary table in such cases.

In the following mapping example, one employee may have only one address, and that address belongs to only one employee. We're using bidirectional association here.

Let’s start by learning about the persistent class.

Persistent Classes For One-to-One Mapping

Persistent Classes: Persistent classes in Hibernate are Java classes whose objects or instances will be persisted in database tables. Hibernate performs best when these classes adhere to a few simple conventions, generally known as the Plain Old Java Object (POJO) programming paradigm.
 

Employee.java and Address.java are two persistent classes in our one-to-one mapping hibernate project. Employee class includes a reference to Address class and vice versa.

One to One Mapping


 

Employee.java

package com.codingninjas;  
import javax.persistence.*;  
  
@Entity  
@Table(name="employee")  
public class Employee 
{    
      
    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
    @PrimaryKeyJoinColumn  
    private int emp_Id;    
    private String emp_name,emp_email;    
    @OneToOne(targetEntity=Address.class,cascade=CascadeType.ALL)  
    private Address emp_address;  
    public int getemp_Id() 
    {  
        return emp_Id;  
    }  
    public void setemp_Id(int emp_Id) 
   {  
        this.emp_Id=emp_Id;  
    }  
    public String getemp_name() 
    {  
        return emp_name;  
    }  
    public void setemp_name(String emp_name) 
    {  
        this.emp_name=emp_name;  
    }  
    public String getemp_email()
    {  
        return emp_email;  
    }  
    public void setemp_email(String emp_email) 
    {  
        this.emp_email=emp_email;  
    }  
    public Address getemp_address() 
    {  
        return emp_address;  
    }  
    public void setAddress(Address emp_address) 
   {  
        this.emp_address=emp_address;  
    }    
  
}    
You can also try this code with Online Java Compiler
Run Code


Address.java

package com.codingninjas;  
import javax.persistence.*;  
  
@Entity  
@Table(name="address")  
public class Address 
{    
      
    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
private int add_Id;    
private String add_Line,add_city,add_state,add_country;    
private int add_pincode;    
  
@OneToOne(targetEntity=Employee.class)  
    private Employee employee;  
    public int getadd_Id() 
    {  
        return add_Id;  
    }  
    public void setadd_Id(int add_Id) 
    {  
        this.add_Id=add_Id;  
    }  
    public String getadd_Line() 
    {  
        return add_Line;  
    }  
    public void setadd_Line(String add_Line1) 
    {  
        this.add_Line=add_Line;  
    }  
    public String getadd_city() 
    {  
        return add_city;  
    }  
    public void setadd_city(String add_city) 
    {  
        this.add_city=add_city;  
    }  
    public String getadd_state() 
    {  
        return add_state;  
    }  
    public void setadd_state(String add_state) 
    {  
        this.add_state=add_state;  
    }  
    public String getadd_country()
    {  
        return add_country;  
    }  
    public void setadd_country(String add_country) 
    {  
        this.add_country=add_country;  
    }  
    public int getadd_pincode() 
   {  
        return add_pincode;  
    }  
    public void setPincode(int add_pincode) 
    {  
        this.add_pincode=add_pincode;  
    }  
    public Employee getEmployee() 
    {  
        return employee;  
    }  
    public void setEmployee(Employee employee) 
    {  
        this.employee=employee;  
    }    
} 
You can also try this code with Online Java Compiler
Run Code

Modifying pom.xml File

Pom.xml: Apache Maven is a popular software project management and comprehension tool that is built on a common piece of information known as the Project Object Model (POM). Maven-based projects acquire their compilation, build, reporting, and documentation instructions from an XML file called pom.xml.

Click source in the pom.xml file. Now, insert the dependencies listed below between the <dependencies>..../dependencies> tags. These dependencies are used in Maven projects to add .jar files.

<dependency>    
    <groupId>org.hibernate</groupId>    
    <artifactId>hibernate-core</artifactId>    
    <version>5.3.1.Final</version>    
</dependency> 
   
<dependency>    
    <groupId>com.oracle</groupId>    
    <artifactId>ojdbc14</artifactId>    
    <version>10.2.0.4.0</version>    
</dependency>    

Configuration File

This file provides database and mapping file information.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>    
<!DOCTYPE hibernate-configuration PUBLIC    
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"    
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">    
     
<hibernate-configuration>    
    
    <session-factory>    
        <property name="hbm2ddl.auto">update</property>    
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>    
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>    
        <property name="connection.username">system</property>    
        <property name="connection.password">jtp</property>    
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>    
    <mapping class="com.codingninjas.Address"/>    
    <mapping class="com.codingninjas.Employee"/>    
    </session-factory>    
    
</hibernate-configuration>

Classes To Store And Fetch Data

We define two user classes named store.java and fetch.java to store and fetch data respectively.

Store.java

package com.codingninjas;    
    
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
    
public class Store 
{    
    public static void main(String[] args) 
    {    
          
        StandardServiceRegistry ssr=newStandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); 
        // hibernate metadata 
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
          
        Transaction t=session.beginTransaction();   
          
        Employee emp1=new Employee();    
        emp1.setemp_name("abc def");    
        emp1.setemp_email("emp@gmail.com");    
            
        Address add1=new Address();    
        add1.setadd_Line("New Road, Main City");    
        address1.setemp_city("New City");    
        address1.setemp_state("New State");    
        address1.setemp_country("New Country");    
        address1.setemp_pincode(909081);    
            
        emp1.setAddress(add1);    
        add1.setEmployee(emp1);    
            
        session.persist(emp1);    
        t.commit();    
            
        session.close();    
        System.out.println("Done");    
    }    
}    
You can also try this code with Online Java Compiler
Run Code

 

Output 

Output Tables
 

Fetch.java

package com.codingninjas;    
import java.util.Iterator;    
import java.util.List;  
  
import javax.persistence.TypedQuery;    
import org.hibernate.Session;    
import org.hibernate.SessionFactory;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
    
public class Fetch 
{    
    public static void main(String[] args) 
    {    
        StandardServiceRegistry ssr=newStandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
//hibernate metadata  
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
            
        TypedQuery query=session.createQuery("from Employee");    
        List<Employee> list=query.getResultList();   
            
        Iterator<Employee> itr=list.iterator();    
        while(itr.hasNext()){    
         Employee emp=itr.next();    
         System.out.println(emp.getEmployeeId()+" "+emp.getName()+" "+emp.getEmail());    
         Address address=emp.getAddress();    
         System.out.println(address.getAddressLine1()+" "+address.getCity()+" "+    
            address.getState()+" "+address.getCountry()+" "+address.getPincode());    
        }    
        
        session.close();    
        System.out.println("Done");    
    }    
}   
You can also try this code with Online Java Compiler
Run Code

 

Output 

1 abc def abc@gmail.com  
New Road, Main City, New City, New Country 909081
Done

Frequently Asked Questions

What are the advantages of Hibernate Framework?

A few advantages of Hibernate Framework are as follows : 

  1. The Hibernate Query Language(HQL) is database-independent. 
  2. Hibernate framework offers the facility to create the tables of the database automatically.
  3. It supports Query cache and offers statistics about query and database status.
  4. It is easy to fetch data from multiple tables in hibernate framework. 

What is a Persistent Entity?

A persistent entity represents one row of the database and is always related to some unique hibernate session. Changes to persistent objects are tracked by Hibernate and are saved into the database when commit calls occur. 

What are the four layers of Hibernate architecture? 

The four layers of the Hibernate architecture are:

  • Java application layer
  • Hibernate framework layer
  • Backhand API layer
  • Database layer

Conclusion

This article extensively discusses the different stages of Hibernate Lifecycle. It goes on to explain each stage of Hibernate Lifecycle along with the diagrams and the functions involved.

To hold a tighter grip on the topic, we recommend you go through the blogs: Hibernate EnvironmentHibernate Configuration, Hibernate annotationsOne To Many Annotation, Many To One Annotation and Many to Many Annotations.

We hope that this blog has helped you enhance your knowledge regarding Hibernate Lifecycle, and if you would like to learn more, check out our articles on Coding Ninjas Blogs

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem Design, and many more!

If you want to test your competency in coding, you may check out the Mock Test Series and participate in the Contests organized on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the ProblemsInterview Experiences, and Interview Bundle for placement preparations.

Nevertheless, you may consider our Courses to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass