This example tells about how to map one-to-one relationship using Hibernate.


Consider the following relationship between employee and address.

Emp table

EmpId name sal job deptno AddressId
1 Ajay 3200 MGR 20 1
2

Ameet

6777 CLERK 30 2

Address table

AddressId State City Street Pincode Houseno
1 Bihar patna 23A 545434 H001
2 Bihar patna 44E 545432 H005

Employee has  relationship with “Address” table. Employee has a Address and its unique and that address can't  be assigned  to other employees. This relationship is called  “ one-to-one".

The way  we achieve one-to-one in database system is by creating a primary key in each of the relations or tables,where the associated table will contain the primary key value of the associating table, which is called as foreign key. Here in our case Employee is the associating table whose primary key Emp_id is creating one-to-one relation with the associated table , Address's column id. So each of the employees record represents a unique record in Address table.

For Achiving this relationship in Hibernate,  we will have to follow these steps

Step1: Create Employee and Address classes

Employe.java

package com.bullraider.onetoone;
import java.io.Serializable;

public class Employee implements Serializable{
    private long empid;
    private String ename;
    private int sal;
    private String job;
    private int deptno ;
    private Address employeeAddress;
    public Employee( String ename, String job, int sal,int deptno) {
        this.deptno = deptno;
        this.ename = ename;
        this.job = job;
        this.sal = sal;
    }

    public long getEmpid() {
        return empid;
    }

    public void setEmpid(long empid) {
        this.empid = empid;
    }
    
    public String getEname() {
        return ename;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public int getSal() {
        return sal;
    }
    public void setSal(int sal) {
        this.sal = sal;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public int getDeptno() {
        return deptno;
    }
    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }
    
    public Address getEmployeeAddress() {
        return employeeAddress;
    }

    public void setEmployeeAddress(Address employeeAddress) {
        this.employeeAddress = employeeAddress;
    }
}


Address.java

package com.bullraider.onetoone;

public class Address {
    
    private long addressId;
    private String street;
    private String state;
    private String city;
    private String pincode;
    private String houseno;
    
    public Address(String city, String state, String street,String pincode,String houseno) {
        this.city = city;
        this.pincode = pincode;
        this.state = state;
        this.street = street;
        this.houseno=houseno;
    }
       
    public String getHouseno() {
        return houseno;
    }
    public void setHouseno(String houseno) {
        this.houseno = houseno;
    }
        public long getAddressId() {
        return addressId;
    }
    public void setAddressId(long addressId) {
        this.addressId = addressId;
    }    
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getPincode() {
        return pincode;
    }
    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}



Step2: Design hbm file for both Employee and Address and define one-to-one in Employee.hbm.xml to Address Table.

Employee.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.bullraider.onetoone.Employee"
        table="emp10">
        <meta attribute="class-description"> This class contains employee details. </meta>
        <id name="empid" type="long" column="empid">
            <generator class="native" />
        </id>
        <property name="ename" type="string" column="ename" not-null="true" />
        <property name="job" type="string" column="job" not-null="true" />
        <property name="sal" type="integer" column="sal" not-null="true" />
        <property name="deptno" type="integer" column="deptno"
            not-null="true" />
        <many-to-one name="employeeAddress" class="com.bullraider.onetoone.Address" column="addressId" cascade="all" unique="true"/>
    </class>
</hibernate-mapping>

NOTE: Within <Many-to-one> relationship we can create <one-to-one> , but we have to addd an attribute unique="true". You still can create this relation by using <one-to-one> element.

Address.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.bullraider.onetoone.Address" table="add_emp10">
        <meta attribute="class-description"> This class contains address details. </meta>
        <id name="addressId" type="long" column="addressId">
            <generator class="native" />
        </id>
        <property name="street" type="string" not-null="true" />
        <property name="city" type="string" not-null="true" />
        <property name="state" type="string" not-null="true" />
        <property name="pincode" type="string" not-null="true" />
        <property name="houseno" type="string" not-null="true" />
    </class>
</hibernate-mapping>


Employee.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.bullraider.onetoone.Employee"
		table="emp10">
		<meta attribute="class-description"> This class contains employee details. </meta>
		<id name="empid" type="long" column="empid">
			<generator class="native" />
		</id>
		<property name="ename" type="string" column="ename" not-null="true" />
		<property name="job" type="string" column="job" not-null="true" />
		<property name="sal" type="integer" column="sal" not-null="true" />
		<property name="deptno" type="integer" column="deptno"
			not-null="true" />
		<many-to-one name="employeeAddress" class="com.bullraider.onetoone.Address"   column="addressId" cascade="all" unique="true"/>
	</class>
</hibernate-mapping>

Step4: Create hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
        <property name="hibernate.connection.username">cat</property>
        <property name="connection.password">tiger</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="show_sql">true</property>
       <property name="hbm2ddl.auto">create-drop</property>
         <mapping resource="com/bullraider/onetoone/Address.hbm.xml"/>
        <mapping resource="com/bullraider/onetoone/Employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


Step5: Create HibernateUtil Class

package com.bullraider.onetoone.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("SessionFactory creation failed" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}



Step 6: Design main class

package com.bullraider.onetoone;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.bullraider.onetoone.util.HibernateUtil;
public class Main {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            Employee employee=new Employee("Pradeep","SALESMAN",12000,10);
       
            Address address=new Address("Bangalore","Karnattaka","a001","560044","H001");
            employee.setEmployeeAddress(address);
            session.save(employee);
            transaction.commit();
            System.out.println("Records inserted sucessessfully");
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

download zip