Home » Enterprise Java » hibernate » Hibernate Many to One Mapping Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Hibernate Many to One Mapping Example

Welcome readers, in this tutorial, we will discuss the Hibernate many to one relationship mapping. As the name suggests, Many to One entity-relationship shows the association of multiple entities with a single entity.

1. Introduction

  • Object-Relational Mapping or ORM is the programming technique to map application domain model objects to the relational database tables
  • Hibernate is a Java-based ORM tool that provides the framework for mapping application domain objects to the relational database tables and vice versa. It provides the reference implementation of the Java Persistence API that makes it a great choice as an ORM tool with benefits of loose coupling
  • A Framework that an option to map plain old Java objects to the traditional database tables with the use of JPA annotations as well as XML based configuration
Hibernate Many to One - Overview
Fig. 1: Hibernate Overview

1.1 Annotations in Hibernate

  • Hibernate annotations are the newest way to define mappings without the use of a XML file
  • Developers use annotations to provide metadata configuration along with the Java code. Thus, making the code easy to understand
  • XML provides the ability to change the configuration without building the project. Thus, annotations are less powerful than the XML configuration and should only be used for table and column mappings
  • Annotations are preconfigured with sensible default values, which reduce the amount of coding required. For e.g., Class name defaults to Table name and Field names default to Column names

The below table lists the commonly used annotations in hibernate –

AnnotationModifierDescription
@Entity Marks a class as a Hibernate Entity (Mapped class)
@TablenameMaps this class with a database table specified by name modifier. If the name is not supplied, it maps the class with a table having the same name as the class
@Id Marks this class field as a primary key column
@GeneratedValue Instructs database to generate a value for this field automatically
@ColumnnameMaps this field with table column specified by name and uses the field name if name modifier is absent
@ManyToOnecascadeIt defines the flow of operations to associated entities. By default, none of the operations are cascaded. For e.g.: @ManyToOne(cascade = CascadeType.ALL)

To understand the above concept, let us open the eclipse ide and implement the many-to-one mapping in the hibernate framework! Do note, we are assuming while practicing this code you already have MySQL database installed on your machines.

2. Hibernate Many to One Mapping Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse, JDK 8, MySQL database and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the application.

Hibernate Many to One - Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Hibernate Many to One - Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Hibernate Many to One - Project Details
Fig. 4: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Hibernate Many to One - Archetype Parameters
Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate.mapping.manytoone</groupId>
	<artifactId>Hibernate-manytoone-mapping-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

We can start adding the dependencies that developers want like Hibernate, MySQL, etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Hibernate framework and the MySQL connector. Maven will automatically resolve the rest dependencies such as Persistence etc. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.hibernate.mapping.manytoone</groupId>
	<artifactId>Hibernate-manytoone-mapping-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>Hibernate Many-to-One Mapping Example</name>
	<description>A tutorial to demonstrate the many-to-one mapping in hibernate.</description>

	<dependencies>
		<!-- Hibernate 4.3.6 Final -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.6.Final</version>
		</dependency>
		<!-- Mysql Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Department Model Class

This class maps the model attributes with the table column names. Add the following code to the model definition to map the attributes with the column names.

Department.java

package com.jcg.hibernate.manytoone.mapping;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name= "department_tbl")
public class Department {

	@Id
	@GeneratedValue
	@Column(name= "department_id")
	private long id;
	
	@Column(name= "department_name")
	private String name;
	
	@Column(name= "department_site")
	private String site;

	public Department() {	}

	public Department(String departmentName, String departmentSite) {
		this.name = departmentName;
		this.site = departmentSite;
	}

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSite() {
		return site;
	}
	public void setSite(String site) {
		this.site = site;
	}
}

3.2.2 Implementation of Employee Model Class

This class maps the model attributes with the table column names and establishes a many-to-one relationship with the department. Add the following code to the model definition to map the attributes with the column names.

Employee.java

package com.jcg.hibernate.manytoone.mapping;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name= "employee_tbl")
public class Employee {

	@Id
	@GeneratedValue
	@Column(name= "employee_id")
	private long id;
	
	@Column(name= "employee_name")
	private String name;
	
	@ManyToOne(cascade= CascadeType.ALL)
	private Department department;

	public Employee() {	}

	public Employee(String employeeName, Department employeeDepartment) {
		this.name = employeeName;
		this.department = employeeDepartment;
	}

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Department getDepartment() {
		return department;
	}
	public void setDepartment(Department department) {
		this.department = department;
	}
}

3.2.3 Implementation of Main Class

Add the following code to the implementation class for understanding the many-to-one entity-relationship in the hibernate framework.

AppMain.java

package com.jcg.hibernate.manytoone.mapping;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class AppMain {

	private static SessionFactory buildSessionFactory() {
		// Creating Configuration Instance & Passing Hibernate Configuration File
		Configuration configObj = new Configuration();
		configObj.configure("hibernate.cfg.xml");

		// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
		ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); 

		// Creating Hibernate SessionFactory Instance
		SessionFactory sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
		return sessionFactoryObj;
	}

	public static void main(String[] args) {
		Session sessionObj = null;

		System.out.println("\n.......Hibernate Many To One Mapping Example.......\n");
		try {
			// Getting Session Object From SessionFactory.
			sessionObj = buildSessionFactory().openSession();

			sessionObj.beginTransaction();

			Department department = new Department("Technology", "Sector 18, Gurugram");

			// By using cascade=all option the department need not be saved explicitly when the employee object is persisted the department will be automatically saved.
			Employee employee1 = new Employee("ABC", department);
			Employee employee2 = new Employee("XYZ", department);

			sessionObj.save(employee1);
			sessionObj.save(employee2);

			// Committing The Transactions To The Database.
			sessionObj.getTransaction().commit();

			System.out.println("\n.......Records Saved Successfully To The Database.......\n");
		} catch(HibernateException hibernateException) {
			if(sessionObj != null && 
					sessionObj.getTransaction() != null) {
				System.out.println("\n.......Transaction Is Being Rolled Back.......");
				sessionObj.getTransaction().rollback();
			}
			hibernateException.printStackTrace();
		} finally {
			if(sessionObj != null) {
				sessionObj.close();
			}
		}
	}
}

3.3 Hibernate Configuration File

In the configuration file, we will include the database and the mapping class details.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- SQL Dialect. -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

		<!-- Database Connection Settings. -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatemapping</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>

		<!-- Echo sql queries to the console. -->
		<property name="show_sql">true</property>
		<!-- Drop & Re-create the database schema on startup. -->
		<property name="hibernate.hbm2ddl.auto">create-drop</property>

		<!-- Specifying Session Context. -->
		<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>

		<!-- Mapping With Model Class Containing Annotations. -->
		<mapping
			class="com.jcg.hibernate.manytoone.mapping.Department" />
		<mapping class="com.jcg.hibernate.manytoone.mapping.Employee" />
	</session-factory>
</hibernate-configuration>

Important points:

  • Here, we instructed Hibernate to connect to a MySQL database named hibernatemapping and the mapping class to be loaded
  • We have also instructed the Hibernate framework to use MySQLDialect i.e. Hibernate will optimize the generated SQL statements for MySQL
  • This configuration will be used to create a hibernate SessionFactory object
  • hbm2ddl.auto tag will instruct the hibernate framework to create the database table schema at the application startup
  • show_sql tag will instruct the hibernate framework to log all the SQL statements on the console

4. Run the Application

To run the Hibernate application, Right-click on the AppMain class -> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Hibernate Many to One - Run Application
Fig. 6: Run Application

5. Project Demo

Output like below will be displayed in the console.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: alter table employee_tbl drop foreign key FK_er9y9i95n9lvevniedajwgyqt
Hibernate: drop table if exists department_tbl
Hibernate: drop table if exists employee_tbl
Hibernate: create table department_tbl (department_id bigint not null auto_increment, department_name varchar(255), department_site varchar(255), primary key (department_id))
Hibernate: create table employee_tbl (employee_id bigint not null auto_increment, employee_name varchar(255), department_department_id bigint, primary key (employee_id))
Hibernate: alter table employee_tbl add constraint FK_er9y9i95n9lvevniedajwgyqt foreign key (department_department_id) references department_tbl (department_id)
 
Aug 27, 2019 5:11:11 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
 
Hibernate: insert into department_tbl (department_name, department_site) values (?, ?)
Hibernate: insert into employee_tbl (department_department_id, employee_name) values (?, ?)
Hibernate: insert into employee_tbl (department_department_id, employee_name) values (?, ?)
 
.......Records Saved Successfully To The Database.......

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of many-to-one mapping in the hibernate framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of hibernate Many to One mapping.

Download
You can download the full source code of this example here: Hibernate Many to One Mapping Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of