Table of contents
1.
Introduction
2.
Many-to-One in Hibernate using XML 
2.1.
Persistent classes for mappings 
2.1.1.
Customer.java 
2.1.2.
Cars.java
2.2.
Mapping files for persistent classes
2.2.1.
customer.hbm.xml 
2.2.2.
cars.hbm.xml 
2.3.
Configuration File
2.3.1.
hibernate_file.cfg.xml
2.4.
User classes for storing and fetching the data
2.4.1.
Store.java
2.4.2.
Fetch.java
3.
Frequently Asked Questions
3.1.
What are the different types of relationships that can be established between entities in Hibernate?  
3.2.
What is a persistent class? 
3.3.
What are the different Hibernate mapping types?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Many to One XML

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

Introduction

There are different relations that are maintained to establish a link between different database tables in relational database models. There can be different types of such relations. A similar concept is there in Hibernate. 

Hibernate works to link the Java language to the database table. Along with this link,  mappings can be established. These mappings are used to navigate through the database. This mapping is defined in the XML sheet.  

So, in this article, we will discuss the Many-to-One relationship in Hibernate using XML. 

Many-to-One in Hibernate using XML 

The first importance here is that Many-to-One is the same as One-to-Many mapping in Hibernate. 

In Many-to-One mapping, various attributes are referred to as one attribute only.

For this article, we will use an example, where one customer can own many cars and one car can belong to only one customer. Here, Many-to-One mapping can be performed using XML.

Persistent classes for mappings 

There are two persistent classes Customer.java and Cars.javaCustomer class contains Cars class reference and vice versa.

Customer.java 

package codingninjas;  
  
public class Customer
{  
	private int customer_id;  
	private String name
	private int phone_numer;  
	private Cars cars;  
	
	// setters and getters methods
}  
You can also try this code with Online Java Compiler
Run Code

 

Cars.java

package codingninjas;  
  
public class Cars
{  
	private int car_id;  
	private String state;  
	private int number;  
	private Customer customer;   


	// setters and getters methods
}  
You can also try this code with Online Java Compiler
Run Code

Mapping files for persistent classes

The two mapping files are customer.hbm.xml and cars.hbm.xml.

customer.hbm.xml 

This is the mapping file for the Customer class, which is a Many-to-One mapping type. 

<?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="codingninjas.Customer" table="cust">  
		<id name="customer_id">  
          	<generator class="increment"></generator>    
        </id>  
        <property name="name"></property>  
        <property name="phone_number"></property>  
     </class>         
</hibernate-mapping>  

 

cars.hbm.xml 

This is the simple mapping file for the Cars class. Note that we are using the generator class.

<?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="codingninjas.cars" table="carst">  
	<id name="car_id">  
		<generator class="increment"></generator>   
	</id>  
	<property name="state"></property>  
	<property name="number"></property>  
                     
	<many-to-one name="customer"></one-to-one>  
</class>          
</hibernate-mapping>    

Configuration File

This file has the information about the database and mapping file. 

hibernate_file.cfg.xml

<?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">    
     
<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="cars.hbm.xml"/>    
    <mapping resource="customer.hbm.xml"/>    
    </session-factory>    
    
</hibernate-configuration>   

User classes for storing and fetching the data

Store.java

package codingninjas;    
    
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 Store 
{    
	public static void main(String[] args) 
	{    
      
    	StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate_file.cfg.xml").build();  
    	Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
      
    	SessionFactory factory=meta.getSessionFactoryBuilder().build();  
    	Session session=factory.openSession();  
      
    	Transaction t=session.beginTransaction();   
      
    	Customer cust1=new Customer();    
    	cust1.setName("Abc Def");    
    	cust1.setPhno(999999999);     
        
    	Cars car1=new Cars();    
    	car1.setState("Kerala");    
    	car1.setNumber(7654);     
   
    	Cars car2=new Cars();    
    	car2.setState("Bihar");    
    	car2.setNumber(4321);   
         
   		car1.setCustomer(cust1);    
   		car2.setCustomer(cust1);
        
    	session.persist(car1);  
    	session.persist(car2);   
    	t.commit();    
        
    	session.close();    
    	System.out.println("Done");    
 	}    
}    
You can also try this code with Online Java Compiler
Run Code


Output

Done

 


Fetch.java

package codingninjas;    
  
import java.util.*;  
import javax.persistence.TypedQuery;  
import org.hibernate.Session;    
import org.hibernate.SessionFactory;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
    
public class Fetch 
{    
	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 Customer c");    
    	List<Customer> list=query.getResultList();    
        
    	Iterator<Customer> itr=list.iterator();    
    	while(itr.hasNext())
    	{    
			Customer c1=itr.next();    
     		System.out.println(c1.getCustomerId()+" "+emp.getName()+" "+emp.getNumber());    
     		Cars car1=c1.getCars();    
     		System.out.println(car1.getCarId()+" "+car1.getState()+" "+    
        	car1.getNumber());    
    	}     
    
    	session.close();    
    	System.out.println("Done");    
	}    
}    
You can also try this code with Online Java Compiler
Run Code


Output 

1 Abc Def 999999999
Kerala 7654
1 Abc Def 999999999
Bihar 4321 
Done 

Must Read:  Java List Iterator

Frequently Asked Questions

What are the different types of relationships that can be established between entities in Hibernate?  

In a Many-to-One relationship, one attribute is mapped to another attribute such a way that one attribute is mapped to many other attributes. 

What is a persistent class? 

Persistent classes in Hibernate are Java classes whose objects or instances will be stored in database tables. 

What are the different Hibernate mapping types?

Different Hibernate mapping types include date and time, binary and large objects, JDK linked, and primitive types. 

Conclusion

This article extensively discusses the concept of Many to One XML in detail along with the code involved. 

To hold a tighter grip on the topic, we recommended reading some more blogs: Interview QuestionsXML encoding, and JSON vs XML.
We hope that this blog has helped you enhance your knowledge regarding One-to-One XML, and if you would like to learn more, check out our articles on Coding Ninjas Blogs

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem 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 organized on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the ProblemsInterview Experiences, and Interview Bundle for placement preparations.

Nevertheless, you may consider our Courses to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass