Hibernate: Performing One-To-One Unidirectional Mapping Using XML Mapping

Contents

Pre-Requisite

Concept Overview

Required Libraries

Diagrammatic Representation

Sample Program


In this tutorial we model a one to one relationship between two entities and then perform basic database operations like insert, update, select and delete on them.


This tutorial is divided primarily into the following sections:

  1. Concept Overview
  2. Sample program

Pre-requisite

  • Basic familiarity with JDBC (Java DataBase Connectivity) API.
  • Relationship between entities in database using primary key and foreign key constraints.
  • Performaing basic database operations on an entity (see this tuturial for further details)

Concept Overview

In real life, Entities can have inter-relationships among themselves. e.g. A School has many Students, a Social Event can have many Participants and once Participant can attend many Social Events, etc.

The key elements of relationship between two entities are Cardinality and Directionality.

Cardinality:
It represents the
number
of the entity under a relationship e.g. If one Person has one Address then the cardinality of Person and Address is one. The cardinality of a relationship could be one-to-one, one-to-many or many-to-many.

Directionality:
It represents the allowable way to navigate from one entity to another e.g. If there is a unidirectional relationship from Person to Address, then if one has an instance of Person object then one can traverse from Person object to Address object but not vice-versa. The directionality could typically be unidirectional (from one entity to another) or bi-directional.

In this sample program, we shall consider a one-to-one relationship between a Person entity and Address entity with unidirectional navigation from Person to Address entity.

Required Libraries

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.4.Final.jar
  • hibernate-core-4.3.5.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • hsqldb.jar
  • jandex-1.1.0.Final.jar
  • javassist-3.18.1-GA.jar
  • jboss-logging-3.1.3.GA.jar
  • jboss-logging-annotations-1.2.0.Beta1.jar
  • jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  • log4j.jar

Diagrammatic Representation




Sample Program

Source Package Structure

Source Code


Create the Person class (see below) that represents an entity involved in the one-to-one relationship.

Create the members personId, firstName, lastName and address (see lines 6-12 below) and the corresponding accessor methods (see lines 26-49 below).

In particular, note that the Address member represents the one-to-one relationship between Person and Address class (see line 12 below).


Create the Address class (see below) which represents the other entity involved in one-to-one relationship.

Create members personId, street, city, state and zipCode (see lines 6-11 below).

In particular, note that there is reference to personId (see line 6 below) that represents the relationshp between Address and Person. However, it is important to notice that there is no reference of Person class within the Address class. Thus if we get a reference to the Address object then we cannot get a reference to the Person object.

However, we have seen
earlier
that if we get a reference to the Person object then we can get a reference to the Address object.

This demonstates how to model a one-to-one unidirectional relationship between Person and Address entities.


Create Person.hbm.xml as shown below.

Map the Person class to PERSON table (see line 6 below).

Map the identifier personId to the corresponding primary key PERSON_ID (see line 7 below).

Map the other members firstName and lastName to their corresponding columns (see lines 10-11 below).

Map the one to one relationship between Person and Address using the
one-to-one
tag (see line 15 below). Note that Hibernate provides a very direct and evocative way to map a one to one relationship by using the
one-to-one
tag.


Create the Address.hbm.xml mapping file as shown below.

Map the Address class to ADDRESS table (see line 6 below).

Map the identifier personId with the PERSON_ID column (see line 7 below)

Note that PERSON_ID column in ADDRESS table is a foreign key corresponding to PERSON_ID in Person table (see
Person.hbm.xml mapping
). This is how the one to one relationship is maintained in the database.

Map the other members like street, city, state and zipCode to their corresponding columns (see lines 10-13 below)


Create the Hibernate Configuration File as shown below. The key elements of this file are:

  • Database connection settings (see lines 8-11 below)
  • Hibernate dialect for HyperSQL database (see line 15 below)
  • Reference to Person and Address mapping files (see lines 33-34 below)


Create the configuration file for Log4J which is used to log the output of the sample program.


Create the HibernateUtil class which is utility class to create Hibernate SessionFactory.

The important sections in this class are:

  • Load Hibernate configuration file (see lines 14-15 below)
  • Build thie session factory using this configuration (see line 21 below)


Create the client program that performs basic database operations like adding, updating, fetching and removing a Person entity that has a one to one relationship with Address entity.

For more details on performing basic database operations refer to
here

  • Create the addPerson() method (see lines 17-30 below) using Session.save() method (see line 26 below)
  • Create the fetchAllPersons() methods (see lines 32-48 below) using Criteria API
  • Create the updatePerson() method (see lines 50-65 below). First fetch the Person with personId as 1 (see lines 55-59 below) and then modify the name of the Person (see line 60 below)
  • Create the removePerson() method (see lines 67-82 below). First fetch the Person with personId as 1 (see lines 72-75 below) and then remove the Person using Session.delete() (see line 78 below)
  • Create the execute() method (see lines 85-106 below) and make calls to create, update and remove Person while fetching the list of all the Persons after every call.
  • Create the main() method (see lines 108-110 below) and then call execute() method from within main method.

This sample program has been packaged as a jar installer which will copy the source code (along with all necessary dependencies) on your machine and automatically run the program for you as shown in the steps below. To run the sample program, you only need Java Runtime Environment (JRE) 1.5 or above on your machine and nothing else.

Download And Automatically Run Sample Program
  • Save hibernateonetooneunidirectionalxml-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment
    (Alternatively you can go the folder containing the hibernateonetooneunidirectionalxml-installer.jar and execute the jar using java -jar hibernateonetooneunidirectionalxml-installer.jar command)
  • You will see a wizard as shown below:
  • Enter the location of the directory where you want the program to install and run (say, C:\Temp)
  • The installer will copy the program on your machine and automatically execute it. The expected output indicating that the program has run successfully on your machine is shown in the image below:
    • Database contents after adding a Person along with his Address
    • Database contents after updated the name of the Person to Abigate Updated
    • The output indicating that No Persons Exist after removing the Person from database

    This demonstrates the successful exection of the sample program to perform basic database operations like insert, update, select and delete on entities having one-to-one unidirectional relationship.

Browsing the Program

This source code for this program is downloaded in the folder specified by you (say, C:\Temp) as an eclipse project called hibernatebasiccrudoperations. All the required libraries have also been downloaded and placed in the same location. You can open this project from Eclipe IDE and directly browse the source code. See below for details of the project structure.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.