Table of contents
1.
Introduction
1.1.
Persistent Class having list object
2.
Creating the Persistent Class
3.
Creating the Mapping file
4.
Configuration File
5.
Classes to Store And Fetch Data
6.
Frequently Asked Questions
6.1.
How is mapping accomplished in Hibernate?
6.2.
What is HQL?
6.3.
What is the One-to-Many association in Hibernate?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

One to Many XML

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

Introduction

We must use one-to-many association to map the list element if the persistent class contains a list object that contains an entity reference.

For example, consider the Forum scenario in which one question has multiple answers.

One Question having multiple answers

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.

Persistent Class having list object

Let's start by learning about the persistent class that has list objects (containing Answer class objects).

package com.codingninjas;  
  
import java.util.List;  
  
public class Question {  
    private int id;  
    private String qname;  
    private List<Answer> answers;  
    //getters and setters  
}
You can also try this code with Online Java Compiler
Run Code

 

Information related to the Answer class includes postedBy, answername, and id.

package com.codingninjas;  
public class Answer {  
    private int id;  
    private String answername;  
    private String postedBy;  
    //getters and setters  
  
    }  
}  
You can also try this code with Online Java Compiler
Run Code


There are list objects with entity references in the Question class (i.e., Answer class object). In this case, we must map this object using a one-to-many list. Let's check out how we can map it.

<list name="answers" cascade="all">  
          <key column="qid"></key>  
          <index column="type"></index>  
          <one-to-many class="com.codingninjas.Answer"/>  
</list> 
You can also try this code with Online Java Compiler
Run Code

Creating the Persistent Class

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.

This persistent class defines the class's attributes, including list.

Question.java

package com.codingninjas;  
  
import java.util.List;  
  
public class Question {  
    private int id;  
    private String qname;  
    private List<Answer> answers;  
  
    //getters and setters  
  
}
You can also try this code with Online Java Compiler
Run Code


Answer.java

package com.codingninjas;  
  
public class Answer 
{  
    private int id;  
    private String answername;  
    private String postedBy;  
    //getters and setters  
  
}  
You can also try this code with Online Java Compiler
Run Code

Creating the Mapping file

In the below implementation, we will be creating a file named question.hbm.xml for defining the list.

question.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
  
          <hibernate-mapping>  
          <class name="com.codingninjas.Question" table="q501">  
          <id name="id">  
          <generator class="increment"></generator>  
          </id>  
          <property name="qname"></property>  
            
          <list name="answers" cascade="all">  
          <key column="qid"></key>  
          <index column="type"></index>  
          <one-to-many class="com.codingninjas.Answer"/>  
          </list>  
            
          </class>  
            
          <class name="com.codingninjas.Answer" table="ans501">  
          <id name="id">  
          <generator class="increment"></generator>  
          </id>  
          <property name="answername"></property>  
          <property name="postedBy"></property>  
          </class>  
            
          </hibernate-mapping>

Configuration File

This file provides database and mapping file information.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  
<!-- Generated by MyEclipse Hibernate Tools.                   -->  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
        <property name="connection.username">system</property>  
        <property name="connection.password">jtp</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
    <mapping resource="question.hbm.xml"/>  
    </session-factory>  
  
</hibernate-configuration>  

Classes to Store And Fetch Data

We define two user classes named store.java and fetch.java to store and fetch data in one-to-many mapping respectively.

Store.java

The data from the question class is stored in this class.

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


public class StoreData 
{    
	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();  
      	
    	Transaction t=session.beginTransaction();    
        	
    	Answer ans1=new Answer();    
    	ans1.setAnswername("Orange is a color.");    
    	ans1.setPostedBy("Coder1");    
        	
    	Answer ans2=new Answer();    
    	ans2.setAnswername("Orange is a fruit");    
    	ans2.setPostedBy("Coder2");    
        	
    	Answer ans3=new Answer();    
    	ans3.setAnswername("Averse is a noun");    
    	ans3.setPostedBy("Coder3");    
        	
    	Answer ans4=new Answer();    
    	ans4.setAnswername("Averse is an adjective");    
    	ans4.setPostedBy("Coder4");    
        	
    	ArrayList<Answer> list1=new ArrayList<Answer>();    
    	list1.add(ans1);    
    	list1.add(ans2);    
        	
    	ArrayList<Answer> list2=new ArrayList<Answer>();    
    	list2.add(ans3);    
    	list2.add(ans4);    
        	
    	Question question1=new Question();    
    	question1.setQname("What is orange?");    
    	question1.setAnswers(list1);    
        	
    	Question question2=new Question();    
    	question2.setQname("What is averse?");    
    	question2.setAnswers(list2);    
        	
    	session.persist(question1);    
    	session.persist(question2);    
        	
    	t.commit();    
    	session.close();    
    	System.out.println("Done");    
    }    
}   
You can also try this code with Online Java Compiler
Run Code

 

Output

Fetch.java

To retrieve every record in the Question class, including the responses, we used HQL. In this instance, it fetches the data from two functionally related tables.

Here, we are directly printing the object of the answer class in this case, but we have overridden the function toString() method in the Answer class, which returns the answername and poster name. As a result, instead of the reference id, it prints the answername and postername.

package com.codingninjas;    
import java.util.*;    
import org.hibernate.*;  
import javax.persistence.TypedQuery;
import org.hibernate.boot.Metadata; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;     
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.MetadataSources; 
    
public class FetchData 
{    
	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 Question");    
    	List<Question> list=query.getResultList();    
        
    	Iterator<Question> itr=list.iterator();    
    	while(itr.hasNext())
    	{    
        	Question q=itr.next();    
        	System.out.println("Question Name: "+q.getQname());    
            
        	//  printing answers    
        	List<Answer> list2=q.getAnswers();    
        	Iterator<Answer> itr2=list2.iterator();    
        	while(itr2.hasNext())  
        	{  
        		Answer a=itr2.next();  
            	System.out.println(a.getAnswername()+":"+a.getPostedBy());  
        	}    
    }  
    session.close();    
    System.out.println("Done");    
    }    
}
You can also try this code with Online Java Compiler
Run Code


Output 

Frequently Asked Questions

How is mapping accomplished in Hibernate?

One of the main components of Hibernate is association mappings. Similar linkages to those in the relational database model are supported. As follows:

  • One-to-one relationships
  • many-to-one relationships
  • many-to-many relationships

What is HQL?

The abbreviation for Hibernate Query Language is HQL. It is a database-independent, object-oriented query language.

What is the One-to-Many association in Hibernate?

In this kind of linkage, a single thing may be connected to numerous other objects. In terms of the mapping, a Set Java collection without any unnecessary elements is used to implement the One-to-Many mapping. The set's One-to-Many element describes the relationship between a single object and many other things.

Conclusion

In this article, we have extensively discussed the One-to-many mapping in hibernate using XML, its example, and file mapping in hibernate project structure.

If you think this blog has helped you enhance your knowledge about One-to-many mapping using XML and if you would like to learn more, check out our articles Hibernate Interview QuestionsOOPS in JavaJava Framework, and JDBC Connection.

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