Table of contents
1.
Introduction 🧩
2.
Creating the Persistent Class for One to Many Mapping 🧑‍💻
3.
Modifying pom.xml File 📁
4.
Configuration File 📁
5.
Classes to Store And Fetch Data 🗃️
6.
Frequently Asked Questions
6.1.
What is a Persistent Entity?
6.2.
What is JPQL?
6.3.
What is a Session?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

One To Many Annotation

Author Harsh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 🧩

Hibernate supports One to Many mapping of persistent class list objects using annotation. For example, consider the Following scenario in which one question has multiple answers.

One to many mapping

There may be multiple answers to a question, and each answer may contain unique information, which is why we used a list in the persistent class to represent a collection of answers. 

To understand one to many mapping we’ll be creating two different tables in MySQL using hibernate both of them will be connected to each other using a foreign key. After that, We will add some data into these tables using HQL. Then we’ll fetch the data from these two tables. Lastly, we’ll print the result on screen. Let’s start by learning about the persistent class

Creating the Persistent Class for One to Many Mapping 🧑‍💻

Persistent classes in Hibernate are Java classes whose objects or instances will be persisted in database tables. Hibernate performs best when these classes adhere to a few simple conventions, generally known as the Plain Old Java Object (POJO) programming paradigm.

List is one of the class properties defined by this persistent class for One to Many mapping.
 

Types.java

package com.codingninjas;
import javax.persistence.*;  
import java.util.List;    
  
@Entity  
@Table(name="types")  
public class Types {    
  
	@Id   
	@GeneratedValue(strategy=GenerationType.TABLE)  
	private int id;    
	private String langType;    
  	
	@OneToMany(cascade = CascadeType.ALL)  
	@JoinColumn(name="pid")
	private List<Languages> languages;

	public int getId() {
		return id;
	}

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

	public String getLangType() {
		return langType;
	}

	public void setLangType(String langType) {
		this.langType = langType;
	}

	public List<Languages> getLanguages() {
		return languages;
	}

	public void setLanguages(List<Languages> languages) {
		this.languages = languages;
	}  

}  
You can also try this code with Online Java Compiler
Run Code


Languages.java

package com.codingninjas;

import javax.persistence.*;  

@Entity  
@Table(name="languages")  
public class Languages{   
	@Id  
	@GeneratedValue(strategy=GenerationType.TABLE)  
	private int id;    
	private String languangeName;    
	private String developer;

	public Languages () {

	}

	public Languages(String languangeName, String developer) {
		this.languangeName = languangeName;
		this.developer = developer;
	}

	public int getId() {
		return id;
	}

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

	public String getLanguangeName() {
		return languangeName;
	}

	public void setLanguangeName(String languangeName) {
		this.languangeName = languangeName;
	}

	public String getDeveloper() {
		return developer;
	}

	public void setDeveloper(String developer) {
		this.developer = developer;
	}
      
}    
You can also try this code with Online Java Compiler
Run Code

Modifying pom.xml File 📁

Pom.xml: Apache Maven is a popular software project management and comprehension tool built on a standard piece of information known as the Project Object Model (POM). Maven-based projects acquire their compilation, build, reporting, and documentation instructions from an XML file called pom.xml.

Click source in the pom.xml file. Insert the dependencies listed below between the dependencies>....</dependencies> tags. These dependencies are used in Maven projects to add .jar files.

<dependencies>
   <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.3.7.Final</version>
        </dependency>
  </dependencies>
  <build>
        <sourceDirectory>src/main/java</sourceDirectory>
  </build>

Configuration File 📁

This file provides database and mapping file information.

hibernate.cfg.xml

<!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>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">2</property>
        <property name="hbm2ddl.auto">update</property>
        
        <!-- dbcp connection pool configuration -->
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>
        
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

        <!-- Mapping classes -->
        <mapping class="com.codingninjas.Types" />
        <mapping class="com.codingninjas.Languages" />
    </session-factory>
</hibernate-configuration>

Classes to Store And Fetch Data 🗃️

We define two user classes named DataStore.java and DataFetch.java to store and fetch data to show One to Many mapping.

DataStore.java

package com.codingninjas;

import java.util.ArrayList;
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  

public class DataStore {    
	public static void main(String[] args) {    
     	
    	StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure().build();  
    	Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      	
    	SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    	Session session=factory.openSession();  
      	
    	Transaction t=session.beginTransaction();    
        	
    	Languages l1 = new Languages("C++", "Bjarne Stroustrup");
    	Languages l2 = new Languages("Java", "James Gosling");
    	
    	Languages l3 = new Languages("perl", "Larry Wall");
    	Languages l4 = new Languages("JavaScript", "Brendan Eich");
    	
     	
    	ArrayList<Languages> list1 = new ArrayList<Languages>();    
    	list1.add(l1);
    	list1.add(l2);

    	ArrayList<Languages> list2 = new ArrayList<Languages>();    
    	list2.add(l3);
    	list2.add(l4);
        	
    	Types type1 = new Types();
    	type1.setLangType("Programming");
    	type1.setLanguages(list1);
    	
    	Types type2 = new Types();
    	type2.setLangType("Scripting");
    	type2.setLanguages(list2);
        	
    	session.persist(type1);    
    	session.persist(type2);    
        	
    	t.commit();    
    	session.close();    
    	System.out.println("success");    
	}    
}   
You can also try this code with Online Java Compiler
Run Code

 

The above program creates two different tables into the database and adds the data to them.

Types Table

Table1 (types)
 

Languages Table

Table2 (Languages)

 

DataFetch.java

To retrieve every record in the Type class, including the languages, we used HQL. In this instance, it fetches the data from two functionally related tables and prints it on screen.

package com.codingninjas;
import java.util.*;  
import javax.persistence.TypedQuery;  
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
    
public class DataFetch {    
	public static void main(String[] args) {    
        	
    	StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
    	Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      	
    	SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    	Session session=factory.openSession();  
        	
    	TypedQuery query=session.createQuery("from Types");    
    	List<Types> list=query.getResultList();    
        	
    	Iterator<Types> itr=list.iterator();    
    	while(itr.hasNext()){    
     	Types t=itr.next();    
        	System.out.println("Language Type: "+t.getLangType());    
            	
        	//printing answers    
        	List<Languages> list2 = t.getLanguages();    
        	Iterator<Languages> itr2 = list2.iterator();    
      	while(itr2.hasNext())  
      	{  
       	Languages l = itr2.next();  
            	System.out.println(l.getLanguangeName() + ", Developed by: " + l.getDeveloper());  
        	}    
    	}  
    	session.close();    
    	System.out.println("success");    
	}    
}    
You can also try this code with Online Java Compiler
Run Code


Output

Output

Frequently Asked Questions

What is a Persistent Entity?

A persistent entity represents one database row and is always related to some unique hibernate session. Changes to persistent objects are tracked by Hibernate and are saved into the database when commit calls occur.

What is JPQL?

The JPA specification is known as the Java Persistence Query Language (JPQL). When constructing the query, it is used.

What is a Session?

It keeps the database and the Hibernate application connected. It offers factory methods that return these instances because it is a factory for Query, Criteria, and Transaction.

Conclusion

In this article, we have extensively discussed the One to Many mapping in hibernate using annotation, its example, and file modifications in hibernate project structure.

If you think this blog has helped you enhance your knowledge about One to Many mapping and if you would like to learn more, check out our articles Hibernate annotationsOne To One AnnotationMany To One Annotation and Many to Many Annotations.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.
 

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass