Hibernate: Performing One-To-One Bidirectional Mapping Using JPA Annotation Mapping



Concept Overview

Required Libraries

Diagrammatic Representation

Sample Program

In this tutorial we model a one to one bidirectional relationship between two entities using JPA annotations.

This tutorial is divided primarily into the following sections:

  1. Concept Overview
  2. Sample program


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

Also see the tutorial on
one to one bidirectional relationship using XML mapping

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 one Participant can attend many Social Events, etc.

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

It represents the
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.

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.

However, In a bidirectional relationship between Person and Address, it is possible to navigate from Person object to Address object and 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 bidirectional navigation between Person to Address entities using JPA annotations.

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

In this sample program, we shall create a one to one bidirectional relationship between Person and Address entities. We shall create these entities in the database and then access them. First we shall Person entity and then traverse it to get the Address entity. Then we shall fetch the Address entity and then traverse it to get the Person entity. This way we shall verify the bidirectionality of the relationship. We shall use JPA annotations for mapping this relationship.

Source Package Structure

Source Code

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

Map the Person class to the PERSON table using @Table annotation. Also mark it as persistable entity using @Entity annotation (see lines 11-13 below).

Create the member personId, map it to the PERSON_ID column and mark it as an identifier using @Id annotation (see lines 16-18 below).

Create the members firstName and lastName and map them to the corresponding columns (see lines 23-23 below).

Create the member address (see line 28 below). Create a one-to-one relationship between Person and Address using @OneToOne annotation (see line 26 below). The one-to-one relationship between the two entities is maintained in the database using using the foreign key ADDRESS_ID. This is indicated to Hibernate by using the @JoinColumn annotation (see line 27 below).

Create the accessor methods (see lines 42-65 below).

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

Mark the Address class as a persistable entity by using the @Entity annotation and map it to the ADDRESS table by using the @Table annotation (see lines 9-11 below).

Create a member addressId and mark it as an identifier by using the @Id annotation and map it to the ADDRESS_ID column by using the @Column annotation (see lines 14-16 below).

Create other members like street, city, state and zipCode and map them to their corresponding columns (see lines 18-31 below).

Create a member person and map the one-to-one relationship using @OneToOne annotation (see lines 30-31 below).

Create the accessor methods (see lines 48-94 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 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 (as shown below) that performs add a Person along with his address and then fetches both Person and Address entities.

For more details on performing basic database operations refer to

  • Create the addPerson() method (see lines 16-29). Create a Person along his Address and save it to the database using Session.save() (see lines 21-25 below)
  • Create the fetchAllPersons() method (see lines 31-44 below) using Criteria API. From the Person object access the Address (see line 39 below)
  • Create the fetchAddAddresses() method (see lines 46-59 below) using Criteria API. From the Address object access the Person (see line 54 below)
  • Create the execute() method (see lines 63-80) and make calls to addPerson(), fetchAllPersons() and fetchAllAddresses() method
  • Create the main() method (see lines 82-84 below) and call execute() 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 hibernateonetoonebidirectionalannotation-installer.jar on your machine
  • Execute/Run the jar using Java Runtime Environment
    (Alternatively you can go the folder containing the hibernateonetoonebidirectionalannotation-installer.jar and execute the jar using java -jar hibernateonetoonebidirectionalannotation-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:
    • Adding a Person and his Address to database
    • Fetching the Person entity and then accessing the Address entity

    • Fetching the Address entity and then accessing the Person entity

    This demonstrates the successful exection of mapping a one to one bidirectional relationship using JPA Annotations using Hibernate.

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 Comment