Hibernate: Performing One-To-One Unidirectional Mapping Using JPA Annotations

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. We shall use JPA annotations for performing the mapping.


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 personId member mark it as an identifier using @Id annotation and map it to the column PERSON_ID using the @Column annotation (see lines 18-20 below)
  • Create the members firstName and lastName and map them to their corresponding columns (see lines 23-28 below)
  • Create a member named address (see line 33 below). Define Address such that it has a one to one relationship with the Person using the @OneToOne annotation (see line 31 below). Also assign the address member to the column ADDRESS_ID using @JoinColumn annotation. This defines the ADDRESS_ID column in PERSON table as a foreign key to the ADDRESS_ID column in ADDRESS table (see diagrammatic representation for more details. Also see Address entity


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

  • Create the addressId member, mark it as an identifier using @Id annotation and map it to the column ADDRESS_ID using the @Column annotation (see lines 13-15 below)
  • Create other members like street, city, state and zipCode and map them to their corresponding columns using @Column annotation (see lines 17-31 below)

Note that there is no reference of Person class within the Address class. Hence this is a unidirectional mapping from Person to Address.


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 classes (see lines 32-33 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 hibernateonetooneunidirectionalannotation-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment
    (Alternatively you can go the folder containing the ?-installer.jar and execute the jar using java -jar hibernateonetooneunidirectionalannotation-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 using JPA Annotations.

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.


1 thought on “Hibernate: Performing One-To-One Unidirectional Mapping Using JPA Annotations”

Leave a Comment