Hibernate One-to-One Mapping Example

One-to-One Hibernate Mapping

In One-to-One association mapping, one object of a persistent class is related to one object of another persistent class. Here, we are going to create an example of one-to-one mapping using annotation. In this case, we are using bidirectional mapping, and no foreign key will be created in the primary table.

In this example, we will take two persistent classes, i.e., Student and Address. We are using bidirectional mapping, so that, one student can have one address and vice-versa. Here, we need to define @OneToOne annotation in the persistent classes.

Following are the steps to create the example:

  1. Create all  POJO classes

In this step, we are going to create persistent classes, i.e., Student.java and Address.java. Both the classes contain the reference of each other.

Student.java

import javax.persistence.CascadeType;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.OneToOne;
 import javax.persistence.Table;
 @Entity
 @Table(name="students")
 public class Student {
  @Id
  @Column(name="sid")
  private int id;
  @Column(name="sname")
  private String name;
  @Column(name="crs")
  private String course;
  @OneToOne(targetEntity=Address.class,cascade=CascadeType.ALL)
  private Address address;
  public Address getAddress() {
  return address;
  }
  public void setAddress(Address address) {
  this.address = address;
  }
  public int getId() {
  return id;
  }
  public void setId(int id) {
  this.id = id;
  }
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  public String getCourse() {
  return course;
  }
  public void setCourse(String course) {
  this.course = course;
  }
  } 

Address.java

import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
 import javax.persistence.OneToOne;
 import javax.persistence.Table;
 @Entity
 @Table(name="address")
 public class Address {
  @Id
  @Column(name="Aid")
  private int addressid;
  @Column(name="add")
  private String address;
  @Column(name="state")
  private String state;
  @Column(name="pin")
  private int pincode;
  @OneToOne(targetEntity=Student.class)
  private Student student;
  public int getAddressid() {
  return addressid;
  }
  public void setAddressid(int addressid) {
  this.addressid = addressid;
  }
  public String getAddress() {
  return address;
  }
  public void setAddress(String address) {
  this.address = address;
  }
  public String getState() {
  return state;
  }
  public void setState(String state) {
  this.state = state;
  }
  public int getPincode() {
  return pincode;
  }
  public void setPincode(int pincode) {
  this.pincode = pincode;
  }
  public Student getStudent() {
  return student;
  }
  public void setStudent(Student student) {
  this.student = student;
  }
  } 
  • Create the configuration class

In this step, we are going to create the configuration class (hibernate.cfg.xml) which contains the information of persistent class and the database.

hibernate.cfg.xml


  
  
  
 update 
 org.hibernate.dialect.MySQL5Dialect
 com.mysql.jdbc.Driver
 jdbc:mysql://localhost:3306/hibernate
 root 
 root 
  
  
  
  
  • Create the main class which stores the object of the persistent class

In this step, we are going to create a class which consists of main() method, and stores the objects of persistent classes.

App.java

import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 public class App 
 {
  public static void main( String[] args )
  {
  Configuration cfg= new Configuration().configure("hibernate.cfg.xml");
  SessionFactory factory= cfg.buildSessionFactory();
  Session session= factory.openSession();
  Transaction t= session.beginTransaction();
  Student s= new Student();
  s.setName("Jyotika Sharma");
  s.setCourse("BCA");
  Address a= new Address();
  a.setAddress("E-50 chhatarpur extn");
  a.setState("New Delhi");
  a.setPincode(110074);
  s.setAddress(a);
  a.setStudent(s);
  session.persist(s);
  t.commit();
  session.close();
  System.out.println("saved successfully");
  }
 } 

OUTPUT

One-to-One Hibernate Mapping

TABLE- students

TABLE- students One-to-One Hibernate Mapping

Related Topics

Hibernate Annotation with Example

Hibernate is an ORM (Object-Relational Mapping) tool which simplifies the application development. Hibernate provides a framework which interacts with the data stored in the databases and it also uses the specifications of the...

2 minutes read.

Hibernate Features

1. Lightweight Hibernate is a lightweight framework as it does not contains additional functionalities; it uses only those functionalities required for object-relational mapping. It is a lightweight framework because it uses persistent...

2 minutes read.

Hibernate History and Versions

Next → History of Hibernate Hibernate was developed in 2001 by Gavin king with his colleagues from Circus Technologies. The main aim was to provide better persistence capabilities than those of EJB2, by reducing the...

2 minutes read.

Hibernate first Example

Now we are going to create the first example in Hibernate. We will proceed step by step to develop the first Java application in Hibernate. The steps are listed below:- Create the POJO...

2 minutes read.

Hibernate SessionFactory

Next → Hibernate SessionFactory A SessionFactory is an interface in Hibernate that create the instances of Session interface. It is a heavy weight object, and it is usually created during the application...

3 minutes read.

Lazy Loading in Hibernate

Lazy loading is a fetching technique used for all the entities in Hibernate. It decides whether to load a child class object while loading the parent class object. When we use association mapping...

3 minutes read.

Hibernate Second-Level Cache

The Second-level cache is related to the SessionFactory object. Once the SessionFactory is closed, all the second-level cache data associated with it will be lost. The cache manager will also get closed. Cache provider The...

5 minutes read.

Hibernate Inheritance Joined Table

In this inheritance strategy, mapping of the child class fields is done with the common fields of the parent class in a separate table. In other words, the common entities between the child...

3 minutes read.

Hibernate Session Interface

Hibernate Session Interface A Session is an interface between the Java application and the Hibernate. It is available in the org.hibernate.session package. It should not be kept open for a long time, as it...

4 minutes read.

Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation. There are steps given below for the web app creation. index.jsp This page will show a registration form. It takes the...

2 minutes read.

Hibernate save() vs persist()

Session.save() The session.save() method is used to save the transient object by assigning a generated value or using a current value of the identifier property. In other words, the save() method is used...

3 minutes read.

Hibernate Merge

Hibernate Merge Merge is a method available in Hibernate which is used to update the existing records. However, it creates a copy from the passed entity objects and returns it. In other words, the merge()...

2 minutes read.

Hibernate First-Level Cache

The first-level cache is related to the Session object. First level cache objects of one Session are not visible to the other Sessions, and all the cache data is lost when the Session...

2 minutes read.

Hibernate One-to-Many Mapping

One-to-Many Hibernate Mapping Example In One-to-many association mapping, only one object of a persistent class is related to many objects of another persistent class. It is a relationship in which one (parent) is related...

3 minutes read.

Hibernate Many-to-One Mapping

Many-to-One Hibernate Mapping with Example A Many-to-One association mapping is the reverse of One-to-Many association mapping. For example, many (customers) are associated with one (vendor). In Hibernate, Many-to-One association mapping is applied from child class...

3 minutes read.

Hibernate Tutorial

What is Hibernate? Hibernate is an Object-Relational Mapping (ORM) tool which reduces the difficulty in the application development. Hibernate provides a framework that interacts with the data stored in the databases. It also uses...

3 minutes read.

Cascade in Hibernate

Cascading is a feature in Hibernate, which is used to manage the state of the mapped entity whenever the state of its relationship owner (superclass) affected. When the relationship owner (superclass) is saved/...

3 minutes read.

Hibernate Named Query using Annotation

In annotation-based named query, we use @NamedQuery annotation inside the POJO class. @NamedQuery- It is used to describe a single named query. It consists of four attributes- two of which are compulsory, and...

2 minutes read.

Hibernate Web Application Example

Web Application Example with Hibernate In this section, we create a hibernate web Application. Here we are using a JSP file for presentation. Example of creating a web application using hibernate index.jsp This page will show a...

2 minutes read.

Hibernate Many-to-Many Mapping

Many-to-Many Hibernate Mapping with Example In Many-to-Many association mapping, more than one objects of a persistent class are associated with more than one objects of another persistent class. For example, many (categories) are related to...

3 minutes read.