Hibernate One To One Mapping(XML Mapping) Tutorial

In this tutorial we will discuss how to implement a one-to-one association using XML mapping approach by creating a sample Hibernate application using mysql and eclipse.

In one-to-one relationship, one object of the one pojo class associated with exactly one object of the another pojo class.

Let us consider relationship between student and student_address. one student has only one address so this is an example of one to one relationship.consider the relationship as shown below.


One-to-one Mapping





In this relationship a student has only one address. It is called unidirectional one-to-one association on a foreign key. In this relationship parent table (STUDENT) refers to child table (STUDENT_ADDRESS) by a foreign key (student_id) and the navigation is one-way from the student to the address. it’s possible to know address of a student, but not vice-versa.

Create Database and Tables :

For this example, we used MYSQL Database. Create following two tables STUDENT and STUDENT_ADDRESS in MySQL by following sql script.

CREATE DATABASE IF NOT EXISTS `hibernate_db` 
USE `hibernate_db`;

CREATE TABLE IF NOT EXISTS `student` (
  `student_id` bigint(100) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE IF NOT EXISTS `student_address` (
  `student_id` bigint(100) NOT NULL,
  `address` varchar(100) DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `state` varchar(100) DEFAULT NULL,
  `country` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`student_id`),
  CONSTRAINT `FK_student_address_student` FOREIGN KEY (`student_id`) REFERENCES `student` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Directory Structure of Project :

Create a simple java project in Eclipse, and add hibernate related jar files to the classpath of the project. The final project structure is given below.

One-to-One Mapping

Create Model Classes :

Create two Pojo classes Student.java and StudentAddress.java to model the two tables STUDENT and STUDENT_ADDRESS, respectively.

Student.java

package com.javawebtutor.hibernate.pojo;

public class Student {
	private long id;
	private String firstName;
	private String lastName;
	private String email;
	private String phone;
	private StudentAddress studentAddress;

	public Student(String firstName, String lastName, String email, String phone) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.phone = phone;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public StudentAddress getStudentAddress() {
		return studentAddress;
	}

	public void setStudentAddress(StudentAddress studentAddress) {
		this.studentAddress = studentAddress;
	}

}

StudentAddress.java

package com.javawebtutor.hibernate.pojo;

public class StudentAddress {
	private long id;
	private String address;
	private String city;
	private String state;
	private String country;
	private Student student;

	public StudentAddress() {

	}

	public StudentAddress(String address, String city, String state,
			String country) {
		super();
		this.address = address;
		this.city = city;
		this.state = state;
		this.country = country;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	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 getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

}

Note:- In above model classes, id is common. This is the primary key of STUDENT table that exhibits One-to-one relationship with STUDENT_ADDRESS table.



Hibernate Utility Class :

Create a utility class for creating Hibernate SessionFactory.

HibernateUtil.java

package com.javawebtutor.hibernate.util;

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

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Create Hibernate Mapping Files :

Create two XML files student.hbm.xml and studentaddress.hbm.xml to map the JavaBean classes with the database tables.

student.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 package="com.javawebtutor.hibernate.pojo">

	<class name="Student" table="STUDENT">

		<id name="id" type="java.lang.Long" column="student_id">
			<generator class="native" />
		</id>
		<one-to-one name="studentAddress"
			class="com.javawebtutor.hibernate.pojo.StudentAddress" cascade="save-update"></one-to-one>

		<property name="firstName" column="first_name" />
		<property name="lastName" column="last_name" />
		<property name="email" column="email" />
		<property name="phone" column="phone" />


	</class>
</hibernate-mapping>

studentaddress.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 package="com.javawebtutor.hibernate.pojo">

	<class name="StudentAddress" table="STUDENT_ADDRESS">
		<id name="id" type="long">
            <column name="student_id" />
            <generator class="foreign">
                <param name="property">student</param>
            </generator>
        </id>
        <one-to-one name="student" class="com.javawebtutor.hibernate.pojo.Student"
            constrained="true"></one-to-one>

		<property name="address" type="string">
            <column name="address"></column>
        </property>
        <property name="city" type="string">
            <column name="city"></column>
        </property>
        <property name="state" type="string">
            <column name="state"></column>
        </property>
        <property name="country" type="string">
            <column name="country"></column>
        </property>

	</class>
</hibernate-mapping>

Create Hibernate Configuration File:

Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection details and the mapping files:

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>
		<!-- specify database driver -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url"> jdbc:mysql://localhost/hibernatedb</property>
		<!-- database username -->
		<property name="hibernate.connection.username">root</property>
		<!-- database password -->
		<property name="connection.password">mukesh</property>
		<!-- database dialect, different for different databases -->
		<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</property>
		<!-- true value shows SQL query that is generated by hibrnate -->
		<property name="show_sql">true</property>
		<!-- path of hibernate mapping file -->
		<mapping resource="com/javawebtutor/hibernate/pojo/student.hbm.xml"></mapping>
		<mapping resource="com/javawebtutor/hibernate/pojo/studentaddress.hbm.xml"></mapping>
	</session-factory>
</hibernate-configuration>

In the above hibernate mapping file we are implementing One-to-one relationship. For both the model classes we are using a single primary key id. In studentaddress.hbm file we have defined a foreign identifier generator so that primary it uses primary key of Studenttable.


Create a Test Program :

Following is code of the test program that persists some sample data.

Test.java
package com.javawebtutor.hibernate.client;

import java.util.Date;

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

import com.javawebtutor.hibernate.model.Bank;
import com.javawebtutor.hibernate.model.Customer;
import com.javawebtutor.hibernate.util.HibernateUtil;

public class Test {
	public static void main(String[] args) {
	
		SessionFactory sf = HibernateUtil.getSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();

		Bank bank = new Bank();
		bank.setBankName("HDFC");
		session.save(bank);
		Date birthDate = new java.util.Date();
		birthDate = new java.util.Date(83, 02, 22);
		Customer customer = new Customer("Mukesh", "Kumar", birthDate,
				"8939651567");
		Customer customer1 = new Customer("Ravi", "Raj", birthDate, "12345678");
		customer.setBank(bank);
		customer1.setBank(bank);

		session.save(customer);
		session.save(customer1);

		session.getTransaction().commit();
		session.close();
	}
}



Output :

Now Run Test.java, you will get following output in the eclipse console.

One-to-one Mapping

SQL Output :

Result in the STUDENT table:

One-to-one Mapping

Result in the STUDENT_ADDRESS table:

One-to-one Mapping

Download this example(src+lib) developed in eclipse





comments powered by Disqus