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 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 Query Language (HQL)

Hibernate provides its query language called Hibernate Query Language (HQL). HQL is an object-oriented query language, similar to the native SQL language, and it works with persistent objects. It is a database-independent and...

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 Composite Primary Key

Hibernate Composite Primary Key A Composite Primary Key is a combination of one or more columns that forms a primary key. When a database table contains more than one primary key column, it is...

8 minutes read.

Hibernate N+1 Select Problem

Hibernate N + 1 Select Problem The N + 1 Select problem is a performance issue in Hibernate. In this problem, a Java application makes N + 1 database calls (N = number...

4 minutes read.

Hibernate vs. JPA

What is JPA? JPA stands for Java Persistence API, which defines a set of functionalities, standards, and concepts to the ORM tool. It is a framework used to manage relational databases. It is available...

2 minutes read.

Hibernate Mapping

Hibernate Mapping Association- It means that two or more things are related to each other by some specific relation. In other words, it specifies how the objects are associated with each other. Hibernate mapping is one...

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.

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 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 GeneratedValue Strategies

Hibernate GeneratedValue Strategies Hibernate supports some generation strategies to generate a primary key in the database table. We can access the strategy with the help of @GeneratedValue annotation. @GeneratedValue The @GeneratedValue annotation specifies how to...

3 minutes read.

Hibernate Inheritance - Single Table

Hibernate Inheritance In this inheritance strategy, only one table is created for all the classes involved in the hierarchy with an additional column known as a discriminator column. The discriminator column helps indifferentiating between...

3 minutes read.

Hibernate Named Query Using XML

A named query is a technique used to assemble all the queries (Native SQL and HQL) in a specific location and refer them by some name. It helps in reducing the mess...

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 merge() vs. update()

In Hibernate, both update() and merge() methods are used to convert the detached state object into the persistent state. session.merge() The merge() method is used when we want to change a detached entity into...

2 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 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 vs. JDBC

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...

2 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 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.