Sponsored Links

Ad by Google
In this post we are going to create a project to implement the step by step unidirectional one-to-one association example using hbm.xml file. Before that lets have a look at what exactly one-to-one association in RDBMS ? One-to-One association means, Each row of a table is mapped with exactly one and only one row with another table.

For example, we have passport_detail and person table each row of passport_detail table is mapped with exactly one and only one row of person table. One person has only one passport.

In hibernate one-to-one association can be implemented via two different ways:
  • Primary key associations
  • Unique foreign key associations
In this tutorial we are going to implement 2nd approach unidirectional "unique foreign key associations". For 1st approach follow this tutorial one-to-one primary key associations

Here is an one-to-one association mapping of person and passport_detail table ER diagram:

Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.2.4
  • MySql 5.5
  • Eclipse Juno 4.2
Overview of the Project Structure:

Main Objects of this project are:
  • jar files
  • hibernate.cfg.xml
  • *hbm.xml (mapping files)
  • database

Step 1. Database Script:

CREATE DATABASE `hibernate_tutorial`;

USE `hibernate_tutorial`;

/*Table structure for table `passport_detail` */

DROP TABLE IF EXISTS `passport_detail`;

CREATE TABLE `passport_detail` (
  `passport_id` int(11) NOT NULL AUTO_INCREMENT,
  `passport_number` varchar(255) DEFAULT NULL,
  `date_of_issue` datetime DEFAULT NULL,
  `date_of_expiry` datetime DEFAULT NULL,
  PRIMARY KEY (`passport_id`)

/*Table structure for table `person` */


CREATE TABLE `person` (
  `person_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  `date_of_birth` datetime DEFAULT NULL,
  `passport_id` int(11) NOT NULL,
  PRIMARY KEY (`person_id`),
  UNIQUE KEY `UK_4ywbdqfnn1i820q1x6lj7tc0v` (`passport_id`),
  KEY `FK_4ywbdqfnn1i820q1x6lj7tc0v` (`passport_id`),
  CONSTRAINT `FK_4ywbdqfnn1i820q1x6lj7tc0v` FOREIGN KEY (`passport_id`) REFERENCES `passport_detail` (`passport_id`)

Step 2. Create a Java Project:
Go to File Menu then New->Java Project, and provide the name of the project.

Create a lib folder(Optional):
Right click on your project and create a new folder named it as lib,this step is optional this is just to place all the required jar file. You may put all the jar files anywhere in your system's location, In this project we are putting all the jar files in lib folder.

Step 3. Add libraries(jar files) into project's build path:
required jar files:
  • antlr-2.7.7.jar
  • commons-collections-3.2.1.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.5.Final.jar
  • hibernate-core-4.2.4.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • jandex-1.1.0.Final.jar
  • javassist-3.18.1-GA.jar
  • jboss-logging-3.1.3.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.3-rc-bin.jar
Step 4. Create a hibernate.cfg.xml file: In this project we placed hibernate.cfg.xml file inside src folder.

Here is a complete hibernate.cfg.xml file.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- MYSQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
   <property name="hbm2ddl.auto">update</property>
        <mapping resource="com/hibernate/hbm/xmls/Person.hbm.xml"/>
        <mapping resource="com/hibernate/hbm/xmls/PassportDetail.hbm.xml"/>

Step 5. Create Person.hbm.xml file: Create a mapping file for person table.

Here is a complete Person.hbm.xml file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated 29 Oct, 2014 8:47:37 PM by Hibernate Tools 3.4.0.CR1 -->
    <class name="com.hibernate.hbm.pojo.Person" table="person">
        <id name="personId" column="person_id">
            <generator class="identity" />
        <property name="firstName" column="first_name"/>
        <property name="lastName" column="last_name"/>
        <property name="dateOfBirth" column="date_of_birth" type="java.util.Date"/>
        <many-to-one name="passportDetail" cascade="all" column="passport_id" unique="true" not-null="true"/>

Step 6. Create PassportDetail.hbm.xml file: Create a mapping file for passport_detail table.

Here is a complete PassportDetail.hbm.xml file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!-- Generated 29 Oct, 2014 8:47:37 PM by Hibernate Tools 3.4.0.CR1 -->
    <class name="com.hibernate.hbm.pojo.PassportDetail" table="passport_detail">
        <id name="passportId" type="java.lang.Integer" column ="passport_id">
             <generator class="identity" />
        <property name="passportNo" type="java.lang.String">
            <column name="passport_number" />
        <property name="dateOfIssue" type="java.util.Date">
            <column name="date_of_issue" />
        <property name="dateOfExpiry" type="java.util.Date">
            <column name="date_of_expiry" />

Step 7. Create a Person Pojo class: Person class has all the properties mapped in Person.hbm.xml


package com.hibernate.hbm.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Person {
 private Integer personId;
 private String firstName;
 private String lastName;
 private Date dateOfBirth;
 private PassportDetail passportDetail;
 public PassportDetail getPassportDetail() {
  return passportDetail;

 public void setPassportDetail(PassportDetail passportDetail) {
  this.passportDetail = passportDetail;

 public Integer getPersonId() {
  return personId;

 public void setPersonId(Integer personId) {
  this.personId = personId;

 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 Date getDateOfBirth() {
  return dateOfBirth;

 public void setDateOfBirth(Date dateOfBirth) {
  this.dateOfBirth = dateOfBirth;

 public String toString() {
  return "Person [personId=" + personId + ", firstName=" + firstName
   + ", lastName=" + lastName + ", dateOfBirth=" + 
   new SimpleDateFormat("yyyy-MM-dd").format( dateOfBirth)
   + ", passportDetail[ passportNumber=" + passportDetail.getPassportNo()
   +", dateOfIssue=" + new SimpleDateFormat("yyyy-MM-dd").
   format(passportDetail.getDateOfIssue()) +", dateOfExpiry=" + 
   new SimpleDateFormat("yyyy-MM-dd").format(passportDetail.getDateOfExpiry()) + "]";


Step 8. Create PassportDetail Pojo class: PassportDetail class contains all the properties mapped in PassportDetail.hbm.xml file.


package com.hibernate.hbm.pojo;

import java.text.SimpleDateFormat;
import java.util.Date;

public class PassportDetail {

 private Integer passportId;
 private String passportNo;
 private Date dateOfIssue;
 private Date dateOfExpiry;

 public Integer getPassportId() {
  return passportId;

 public void setPassportId(Integer passportId) {
  this.passportId = passportId;

 public String getPassportNo() {
  return passportNo;

 public void setPassportNo(String passportNo) {
  this.passportNo = passportNo;

 public Date getDateOfIssue() {
  return dateOfIssue;

 public void setDateOfIssue(Date dateOfIssue) {
  this.dateOfIssue = dateOfIssue;

 public Date getDateOfExpiry() {
  return dateOfExpiry;

 public void setDateOfExpiry(Date dateOfExpiry) {
  this.dateOfExpiry = dateOfExpiry;

 public String toString() {
  return "PassportDetail [passportId=" + passportId + ", passportNo="
    + passportNo + ", dateOfIssue=" + new SimpleDateFormat("yyyy-MM-dd").
    format(dateOfIssue) + ", dateOfExpiry=" + 
    new SimpleDateFormat("yyyy-MM-dd").format(dateOfExpiry) +  "]";

Step 9. Create a HibernateUtility class: HibernateUtility class to build SessionFactory vi loading Configuration.

HibernateUtility .java

package com.hbm.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtility {
  private static final SessionFactory sessionFactory = buildSessionFactory();
     private static SessionFactory buildSessionFactory() {
      Configuration configuration = new Configuration();

      ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   return sessionFactory;
     public static SessionFactory getSessionFactory() {
         return sessionFactory;

Step 10. Create PersonDAO class: PersonDAO class to perform insert/update/get/delete records into database.


package com.hibernate.hbm.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hibernate.hbm.pojo.Person;
import com.hibernate.hbm.util.HibernateUtility;

public class PersonDAO {
 private static SessionFactory sessionFactory;
 static {
  sessionFactory = HibernateUtility.getSessionFactory();

 public static Person findById(int id) {
  Session session = sessionFactory.openSession();
  Person person = (Person) session.get(Person.class, id);
  return person;
 public static Person save(Person person) {
  Session session = sessionFactory.openSession();




  return person;

 public static Person update(Person person) {
  Session session = sessionFactory.openSession();




  return person;


 public static void delete(Person person) {
  Session session = sessionFactory.openSession();




 public static List<Person> findAll(){
  Session session = sessionFactory.openSession();
  List<Person> persons = session.createQuery("from Person").list();
  return persons;

Step 11. Create a PersonPassportService class: PersonPassportService class to call the methods of PersonDAO class.


package com.hibernate.hbm.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.hibernate.hbm.dao.PersonDAO;
import com.hibernate.hbm.pojo.PassportDetail;
import com.hibernate.hbm.pojo.Person;

public class PersonPassportService {

 public static void main(String[] args) {
  Person person = new Person();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  PassportDetail passportDetail = new PassportDetail();
  try {
  } catch (ParseException e) {
  // saving person detail into the database.
  // it will generate two insert query, one for person and one for passport detail

That's it, Now run PersonPassportService class you will get output at your console where two insert query will executed one for PassportDetail and one for Person table, along with person details because we are overriding the toString() method inside Person.java pojo class.

Hibernate: insert into passport_detail (passport_number, date_of_issue, date_of_expiry) values (?, ?, ?)
Hibernate: insert into person (first_name, last_name, date_of_birth, passport_id) values (?, ?, ?, ?)
Person [personId=1, firstName=Tony, lastName=Leo, dateOfBirth=1990-10-10, passportDetail[ passportNumber=L1025698, dateOfIssue=2020-10-09, dateOfExpiry=2010-10-10]

Download the complete example from here Source Code

For required jar files you may download it from hibernate.org or from my previous post, here


Sponsored Links


Post a Comment