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

Contents

Pre-Requisite

Concept Overview

Required Libraries

Diagrammatic Representation

Sample Program


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


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)

See
related tutorial
for modeling one to many relationship using XML based 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.

Cardinality:
It represents the
number
of the entity under a relationship e.g. If one Department has many Employees then the cardinality this relationship is one-to-many. 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 Department to Employee, then if one has an instance of Department object then one can traverse from Department object to Employee object but not vice-versa.

However, In a bidirectional relationship between Department and Employee, it is possible to navigate from Department object to Employee 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-many relationship between a Department entity and Employee entity with bidirectional navigation between Department to Employee 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 many bidirectional relationship between Department and Employee entities using JPA annotations. This is a one-to-many relationship i.e. one Department has many Employees.

We shall create these entities in the database and then access them. First we shall fetch Department entity and then traverse it to get the Employee entity. Then we shall fetch the Employee entity and then traverse it to get the Department entity. This way we shall verify the bidirectionality of the one-to-many relationship.

Source Package Structure

Source Code


Create the Department entity as shown below.

  • Mark is as a persistable entity using the @Entity annotation (see line 10 below).
    Map the Department entity to the DEPARTMENT table using @Table annotation (see line 11 below).
  • Create the member id map it to the DEPARTMENT_ID column and mark it as an identifier using @Id annotation (see lines 13-15 below).
  • Create the member name and map to the NAME column by using @Column annotation (see lines 17-18 below).
  • Create the member employees which is a collection of all employees in a department. Map the one-to-many relationship between the Department and Employee entities by using @OneToMany annotation (see lines 20-21 below).


Create a class Employee as shown below:

  • Map the Employee class as a persistable entity (see line 10 below). Also map the Employee class to the EMPLOYEE table (see line 11 below)
  • Map the identifier id to the EMPLOYEE_ID column using @Table annotation (see line 15 below). Also mark it as an identifier using @Id annotation (see lines 14 below)
  • Create other members like name, age and salary and map them to their corresponding columns (see lines 18-25 below)
  • Create the member Department and map the relationship using @ManyToOne annotation (see line 27 below). The foreign key relationship is maintained in the DEPARTMENT_ID column in EMPLOYEE table. This is defined using @JoinColumn annotation (see line 28 below)


Create the Hibernate.cfg.xml 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 Employee and Department 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.

Load the configuration file and build the session factory (see line 12 below)


Create the client program (as shown below) that adds a Department along with its Employees and then fetches both Department and Employee entities.

For more details on performing basic database operations refer to
here

  • Create the insertDepartmentAndEmployees() method (see lines 25-44). Create a Department along its Employess and save it to the database using Session.save()
  • Create the fetchAllDepartments() method (see lines 46-61 below) using Criteria API. From the Department object access the Employees (see line 54 below)
  • Create the fetchAllEmployees() method (see lines 63-74 below) using Criteria API. From the Employee object access the Department (see line 69 below)
  • Create the execute() method (see lines 15-23) and make calls to insertDepartmentAndEmployees(), fetchAllDepartments() and fetchAllEmployees() methods
  • Create the main() method (see lines 76-78 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 ?-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 hibernateonetomanybidirectionalannotation-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 Deparment and its Employees to database
    • Fetching the Department entity and then accessing the Employee entity

    • Fetching the Employee entity and then accessing the Department entity

    This demonstrates the successful exection of mapping a one to many bidirectional relationship using 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 hibernateonetomanybidirectionalannotation. 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