Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Hibernate - One to One using Annotations

One to One mapping can also be achieved in Hibernate and it is a bit easier than the XML mapping.

As stated for XML mapping, say an 'Employee' has only one 'Address' and both 'Employee' and 'Address' are Entities.

In that case we will be going for a 'one to one' mapping.

Let us see the 'Employee' class:


class Employee {

   String id;
   String name;

   @OneToOne(Cascade=CascadeType.ALL)
   Address address;

   ---Getters & Setters---
}


An 'Employee' can have only one 'Address'. So, in the 'Employee' class we have put:

Address address;

Just above the 'Address address' we have put '@OneToOne' annotation and we do not need to specify anything in the mapping file.

The 'Address' class is defined below.


class Address{
   @Id
   @Column(name="ADDRESS_ID")
   int addressId;

   @Column(name="STREET_NAME")
   String streetName;

   @Column(name="CITY")
   String city;

   @Column(name="PIN_CODE")
   String pinCode;

   @OneToOne
   Employee employee;

   ---Getters & Setters---
}


Same logic applies for 'Address' class as well. i.e. There is an One to One mapping and we have put '@OneToOne' just above the Employee reference.

Employee employee;

And our mapping is done.

Now, we will be writing the main class where we will be saving the 'Employee' data and its corresponding 'Address' data to the database using Hibernate.


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSave {
   public static void main(String[] args) {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
     session.beginTransaction();

     Address address = new Address();

     Address address = new Address();
     address.setStreetName("Walls Street");
     address.setCity("Delhi");
     address.setPinCode("110012");

     Employee employee = new Employee();
     employee.setId(1);
     employee.setName("Joe");
     employee.setAddress(address);
     session.save(employee);

     //session.save(localAddress);
     //Don't have to write the above statement as cascade="all" is set in the mapping file.

     session.getTransaction().commit();

     session.close();
     sessionFactory.close();
  }
}

EMPLOYEE

ID NAME
1 Joe

ADDRESS

ID STREET_NAME CITY PIN_CODE
1 Walls street Delhi 110012

So, 'ID' column in the 'EMPLOYEE' table is the foreign key 'ID' in 'ADDRESS' table.