hibernate

Hibernate One to Many Example

One-to-Many mapping means that one row in a table can be mapped to multiple rows in another table but multiple rows can be associated with only one instance of the first entity. It is 1-to-n relationship. For example, in any company, an employee can register multiple bank accounts but one bank account will be associated with one and only one employee.

In this tutorial, we will learn about how to use Hibernate One-To-Many Bidirectional mapping using annotation based configuration.
 
 
 
 

1. Introduction

A One-to-Many entity relationship shows the association of an entity with multiple instances of another entity. Let us take an example of Department and Employee where one department can have many employees and employers can have a many-to-one relationship.

Fig. 1: One-to-Many Relationship Overview
Fig. 1: One-to-Many Relationship Overview

From SQL perspective, table Employee will have a Foreign Key constraint that will point to the Primary Key of the table Department and there can be multiple employees pointing to a single department.

The one-to-many association can be either unidirectional or bidirectional.

  • In unidirectional association, only source entity has a relationship field that refers to the target entities. We can navigate this type of association from one side
  • In bidirectional association, each entity (i.e. source and target) has a relationship field that refers to each other. We can navigate this type of association from both sides

But before we move on, let’s understand the Hibernate and the Annotations.

1.1 Hibernate

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

Fig. 2: Hibernate Overview
Fig. 2: Hibernate Overview

1.2 Hibernate Annotations

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

1.4 Reference Guide on Hibernate Annotations

Hibernate Annotations are based on the JPA 2 specification. All the JPA annotations are defined in the javax.persistence.* package. The basic JPA annotations of Hibernate that can be used in an entity are the ones below.

AnnotationModifierDescription
@EntityMarks 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.
@IdMarks this class field as a primary key column.
@GeneratedValueInstructs 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.
@OneToManycascadeIt defines the flow of operations to associated entities. By default, none of the operations are cascaded. For e.g.: @OneToMany(cascade = CascadeType.ALL).
mappedByThis represent the entity that owns the relationship meaning the corresponding table that has foriegn key column and this element is specified on the non-owning side of the association. For e.g.: @OneToMany(mappedBy = "dept")
targetEntityIf developers are using Java Generics to define the Collection, then this propery is optional. It denotes the entity class that is target of the association. For e.g.: @OneToMany(target = Employee.class)
fetchBy default fetch type is Lazy in all the relationship except for @OneToOne mapping. It defines whether the associated entities be fetched lazily or eagerly. For e.g.: @OneToMany(fetch = FetchType.EAGER)

1.5 Download and Install Hibernate

You can read this tutorial in order to download and install Hibernate in the Eclipse IDE.

1.6 Download and Install MySQL

You can watch this video in order to download and install the MySQL database on your Windows operating system.

Now, open up the Eclipse IDE and let’s see how to implement One-to-Many relationship in Hibernate using Annotation!

2. Hibernate One to Many Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL database and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Hibernate One-to-Many Mapping Application Project Structure
Fig. 3: Hibernate One-to-Many Mapping Application Project Structure

2.3 Project Creation

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

Fig. 4: Create Maven Project
Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select 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 next button to proceed.

Fig. 5: Project Details
Fig. 5: 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.

Fig. 6: Archetype Parameters
Fig. 6: 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>HibernateOneToManyMapping</groupId>
	<artifactId>HibernateOneToManyMapping</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

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

3. Application Building

Below are the steps involved in developing this application.

3.1 Database & Table Creation

The following MySQL script is used to create a database called tutorialDb with 2 tables: student and, marks_details. Note that, student and, marks_details tables exhibit a One-to-Many relationship. Open MySQL terminal or workbench terminal and execute the script:

CREATE DATABASE tutorialDb;
 
USE tutorialDb;
 
CREATE TABLE IF NOT EXISTS student (
  student_id int(100) NOT NULL AUTO_INCREMENT,
  first_name varchar(50) DEFAULT NULL,
  last_name varchar(50) DEFAULT NULL,
  email varchar(50) DEFAULT NULL,
  phone varchar(50) DEFAULT NULL,
  PRIMARY KEY (student_id)
);

CREATE TABLE IF NOT EXISTS marks_details (
  student_id int(100) NOT NULL,
  test_id int(100) NOT NULL AUTO_INCREMENT,
  subject varchar(100) DEFAULT NULL,
  max_marks varchar(100) DEFAULT NULL,
  marks_obtained varchar(100) DEFAULT NULL,
  result varchar(100) DEFAULT NULL,
  PRIMARY KEY (test_id),
  KEY FK_marks_details_student (student_id),
  CONSTRAINT FK_marks_details_student FOREIGN KEY (student_id) REFERENCES student (student_id)
 );

If everything goes well, the tables will be shown in the MySQL workbench. Below diagram shows the Entity relationship between these tables.

Fig. 7: One-to-Many Mapping
Fig. 7: One-to-Many Mapping

3.2 Maven Dependencies

Here, we specify only two dependencies for Hibernate Core and MySQL Connector. Rest dependencies will be automatically resolved by Maven, such as Hibernate JPA and Hibernate Commons Annotations. 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>HibernateOneToManyMapping</groupId>
	<artifactId>HibernateOneToManyMapping</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<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.3 Java Class Creation

Let’s create the required Java files. Right click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation
Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.hibernate.onetomany.mapping.

Fig. 9: Java Package Name (com.jcg.hibernate.onetomany.mapping)
Fig. 9: Java Package Name (com.jcg.hibernate.onetomany.mapping)

Once the package is created in the application, we will need to create the model and implementation classes. Right click on the newly create package: New -> Class.

Fig. 10: Java Class Creation
Fig. 10: Java Class Creation

A new pop window will open and enter the file name as Student. The owner entity class will be created inside the package: com.jcg.hibernate.onetomany.mapping.

Fig. 11: Java Class (Student.java)
Fig. 11: Java Class (Student.java)

Repeat the step (i.e. Fig. 10) and enter the filename as MarksDetails. The mapped entity class will be created inside the package: com.jcg.hibernate.onetomany.mapping.

Fig. 12: Java Class (MarksDetails.java)
Fig. 12: Java Class (MarksDetails.java)

Again, repeat the step listed in Fig. 10 and enter the file name as AppMain. The implementation class will be created inside the package: com.jcg.hibernate.onetomany.mapping.

Fig. 13: Java Class (AppMain.java)
Fig. 13: Java Class (AppMain.java)

3.3.1 Implementation of Owner Entity

@OneToMany annotation defines a many-valued association with one-to-many multiplicity. If the collection is defined using generics to specify the element type, the associated target entity type need not to be specified; otherwise the target entity class must be specified. Here, the mappedBy attribute is mandatory, as it specifies that the One-to-Many association is mapped by this side (i.e. Student); and the cascade attribute make sure Hibernate will save/update the marks details when saving/updating this category. Add the following code to it:

Student.java

package com.jcg.hibernate.onetomany.mapping;

import java.util.Set;

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

@Entity
@Table(name = "student")
public class Student {

	@Id
	@GeneratedValue
	@Column(name = "student_id")
	private long id;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	@Column(name = "email")
	private String email;

	@Column(name = "phone")
	private String phone;

	@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
	private Set marksDetails;

	public Student() { }

	public Student(String firstName, String lastName, String email, String phone) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.phone = phone;
		this.email = email;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Set getMarksDetails() {
		return marksDetails;
	}

	public void setMarksDetails(Set marksDetails) {
		this.marksDetails = marksDetails;
	}
}

3.3.2 Implementation of Mapped Entity

@ManyToOne annotation defines a single-valued association to another entity class that has many-to-one multiplicity. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. @JoinColumn is used to specify a mapped column for joining an entity association. Add the following code to it:

MarksDetails.java

package com.jcg.hibernate.onetomany.mapping;

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

@Entity
@Table(name = "marks_details")
public class MarksDetails {

	@Id
	@GeneratedValue
	@Column(name = "test_id")
	private long testId;

	@Column(name = "subject")
	private String subject;

	@Column(name = "max_marks")
	private String maxMarks;

	@Column(name = "marks_obtained")
	private String marksObtained;

	@Column(name = "result")
	private String result;

	@ManyToOne
	@JoinColumn(name = "student_id")
	private Student student;

	public MarksDetails() { }

	public MarksDetails(String subject, String maxMarks, String marksObtained, String result) {
		this.subject = subject;
		this.maxMarks = maxMarks;
		this.marksObtained = marksObtained;
		this.result = result;
	}

	public long getTestId() {
		return testId;
	}

	public void setTestId(long testId) {
		this.testId = testId;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getMaxMarks() {
		return maxMarks;
	}

	public void setMaxMarks(String maxMarks) {
		this.maxMarks = maxMarks;
	}

	public String getMarksObtained() {
		return marksObtained;
	}

	public void setMarksObtained(String marksObtained) {
		this.marksObtained = marksObtained;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}
}

3.3.3 Implementation of Utility Class

This class helps in creating the SessionFactory from the Hibernate configuration file and interacts with the database to perform the INSERT operation. Add the following code to it:

AppMain.java

package com.jcg.hibernate.onetomany.mapping;

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 {

	static Session sessionObj;
	static SessionFactory sessionFactoryObj;

	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
		sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
		return sessionFactoryObj;
	}

	public static void main(String[] args) {
		System.out.println(".......Hibernate One To Many Mapping Example.......\n");
		try {
			sessionObj = buildSessionFactory().openSession();
			sessionObj.beginTransaction();

			Student studentObj = new Student("Java", "Geek",  "javageek@javacodegeeks.com", "0123456789");
			sessionObj.save(studentObj);

			MarksDetails marksObj1 = new MarksDetails("English", "100", "90",  "Pass");  
			marksObj1.setStudent(studentObj);  
			sessionObj.save(marksObj1);

			MarksDetails marksObj2 = new MarksDetails("Maths", "100", "99",  "Pass");  
			marksObj2.setStudent(studentObj);
			sessionObj.save(marksObj2);

			MarksDetails marksObj3 = new MarksDetails("Science", "100", "94",  "Pass");  
			marksObj3.setStudent(studentObj);
			sessionObj.save(marksObj3);

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

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

3.4. Hibernate Configuration File

To configure the Hibernate framework, we need to implement a configuration file i.e. hiberncate.cfg.xml. Right click on src/main/resources folder, New -> Other.

Fig. 14: XML File Creation
Fig. 14: XML File Creation

A new pop window will open and select the wizard as an XML file.

Fig. 15: Wizard Selection
Fig. 15: Wizard Selection

Again, a pop-up window will open. Verify the parent folder location as HibernateManyToManyMapping/src/main/resources and enter the file name as hibernate.cfg.xml. Click Finish.

Fig. 16: hibernate.cfg.xml
Fig. 16: hibernate.cfg.xml

Once the file is created, we will include the database configuration and mapping classes details. Add the following code to it:

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/tutorialDb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password"></property>
		<property name="show_sql">true</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.onetomany.mapping.Student" />
		<mapping class="com.jcg.hibernate.onetomany.mapping.MarksDetails" />
	</session-factory>
</hibernate-configuration>

Notes:

  • Here, we instructed Hibernate to connect to a MySQL database named tutorialDb and the Mapping classes to be loaded
  • We have also instructed 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

4. Run the Application

To run the Hibernate application, Right click on the AppMain class -> Run As -> Java Application.

Fig. 17: Run Application
Fig. 17: Run Application

5. Project Demo

On executing the AppMain class, you will see the records in student and, marks_details tables. Developers can debug the example and see what happens in the database after every step. Enjoy!

Fig. 18: Application Output
Fig. 18: Application Output

Below is the snapshot of MySQL Database after execution of the above program.

Student Table

Fig. 19: Student Table Records
Fig. 19: Student Table Records

Marks Details Table

Fig. 20: Marks Details Table Records
Fig. 20: Marks Details Table Records

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for Hibernate One-To-Many mapping example tutorial. I hope this article helped you find whatever you were looking for.

7. Download the Eclipse Project

This was an example of Hibernate One-To-Many Mapping.

Download
You can download the full source code of this example here: Hibernate OneToMany Mapping

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
hector pasarin
hector pasarin
6 years ago

Thanks for share, i followed this guide and i had to make some little change to make it work, but now its working fine. I was having a problem in the class Student that generated this error message:

Collection has neither generic type or OneToMany.targetEntity() defined (…)

Then i changed the code of Student.java from:

line 34–> @OneToMany(mappedBy = “student”, cascade = CascadeType.ALL)
line 35–> private Set marksDetails;

to:

@OneToMany(mappedBy = “student”, cascade = CascadeType.ALL)
private Set marksDetails;

and it seems that it work.

hector pasarin
hector pasarin
6 years ago

Uppsss.. it seems that there are difficulties to show the characters smaller than — greater than…

line 34–> @OneToMany(mappedBy = “student”, cascade = CascadeType.ALL)
line 35–> private Set smaller_than_character MarksDetails greater_than_character marksDetails;

Deepak Sharma
Deepak Sharma
6 years ago
Reply to  hector pasarin

i hector, i am receiving the sessionFactoryObj as null, with the same code base. how should i go about it ?

Deepak Sharma
Deepak Sharma
6 years ago

Hi , i downloaded this project and while running i am facing an issue with sessionfactory obj as null

at line no 23 sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);

This is returning me null thus getting me into catch block of main method.
Can you please help me with this ?

Nishith Sarkar
Nishith Sarkar
5 years ago
Reply to  Deepak Sharma

I am also facing the same issue which deepak has mentioned, sessionfactory obj as null resulting in NullPointerException, please suggest.

Nkenna
Nkenna
5 years ago
Reply to  Yatin

how can I connect to the support section, im having similar issues

Back to top button