One to one is a relationship in relational database, it will occur when a parent table record has zero or one child record in child table. In this tutorial, we are going to implement the one to one mapping in hibernate (relationship) using xml configuration.

One to one mapping in hibernate can be achieved in two ways.

In this example, we are implementing the one to one mapping with foreign key using xml configuration.

One to one mapping in hibernate using foreign key :

One to one mapping in hibernate is like many to one relationship, but in the many to one relationship a foreign key column can allow duplicate values. If we prevent the duplicate values in foreign key column then it will act as one to one mapping.

To do so.. To prevent the duplicates in foreign key column, hibernate provides two attributes like unique=”true” and not-null=”true”. We can apply these attributes in <many-to-one> in hibernate mapping file (hbm.xml).

In order to get one to one relationship between two objects, in child class pojo class we need a reference variable of type parent class.

One to One Mapping in Hibernate Example :

one to one mapping in hibernate

If we take the Person and Passport, there is a relationship between Person to Passport is one to one relationship. Because one Person can have only one Passport. We can implement this relationship using hibernate one to one mapping.

Project Structure :

one to one mapping in hibernate Example

Required Dependencies :

pom.xml
<dependencies>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.0.Final</version>
        </dependency>
        <!-- MySQL Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
</dependencies>

Hibernate POJO Classes :

Person.java

Person.java
package com.onlinetutorialspoint.hibernate.pojo;

public class Person {
	private int personId;
	private String personName;
	public int getPersonId() {
		return personId;
	}
	public void setPersonId(int personId) {
		this.personId = personId;
	}
	public String getPersonName() {
		return personName;
	}
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	
}

Passport.java

Passport.java
package com.onlinetutorialspoint.hibernate.pojo;

import java.util.Date;

public class Passport {
    private int passportNumber;
    private Date issudDate;
    private Date expireDate;
    private Person person;
    public Person getPerson() {
        return person;
    }
    public void setPerson(Person person) {
        this.person = person;
    }
    public int getPassportNumber() {
        return passportNumber;
    }
    public void setPassportNumber(int passportNumber) {
        this.passportNumber = passportNumber;
    }
    public Date getIssudDate() {
        return issudDate;
    }
    public void setIssudDate(Date issudDate) {
        this.issudDate = issudDate;
    }
    public Date getExpireDate() {
        return expireDate;
    }
    public void setExpireDate(Date expireDate) {
        this.expireDate = expireDate;
    }

}

Hibernate Mapping Files :

person.hbm.xml

person.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.onlinetutorialspoint.hibernate.pojo.Person" table="person">
        <id name="personId" column="personid" />
        <property name="personName" column="personname" />
    </class>
</hibernate-mapping>

passport.hbm.xml

passport.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.onlinetutorialspoint.hibernate.pojo.Passport"
        table="passport">
        <id name="passportNumber" column="ppid" />
        <property name="issudDate" column="idate" />
        <property name="expireDate" column="edate" />
        <many-to-one name="person" class="com.onlinetutorialspoint.hibernate.pojo.Person"
        column="per_id" unique="true" not-null="true" cascade="all"/>
 </class>
</hibernate-mapping>
On the above mapping file, to represent the one to one relationship, we use <many-to-one> tag. But unique=”true” and not-null=”true” attributes make this <many-to-one> as one to one.

Hibenate Utility:

HibernateUtil.java

HibernateUtil.java
package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private HibernateUtil() {

    }

    private static SessionFactory sessionFactory;

    public static synchronized SessionFactory getInstnce() {

        if (sessionFactory == null) {
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        }
        return sessionFactory;

    }
}

Well! we are almost done.

Run the application

Main.java

Main.java
import java.util.Date;

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

import com.onlinetutorialspoint.hibernate.pojo.Passport;
import com.onlinetutorialspoint.hibernate.pojo.Person;
import com.onlinetutorialspoint.util.HibernateUtil;

public class Main {

    public static void main(String[] args) {

        SessionFactory sessionFactory = HibernateUtil.getInstnce();
        Session session = sessionFactory.openSession();

        Person person = new Person();
        person.setPersonId(1001);
        person.setPersonName("Chandrashekhar");

        Passport passport = new Passport();
        passport.setPassportNumber(12346856);
        passport.setExpireDate(new Date());
        passport.setIssudDate(new Date());
        passport.setPerson(person);

        Transaction transaction = session.beginTransaction();
        session.save(passport);
        transaction.commit();

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

Output :

Terminal
Hibernate: select person_.personid, person_.personname as personna2_1_ from person person_ where person_.personid=?
Hibernate: insert into person (personname, personid) values (?, ?)
Hibernate: insert into passport (idate, edate, per_id, ppid) values (?, ?, ?, ?)

Database Output :

one to one mapping in hibernate output

Happy Learning 🙂

Download Example