Table of contents
1.
Introduction
2.
Persistent Classes For One-to-One Mapping
3.
Modifying pom.xml File
4.
Configuration File
5.
Classes To Store And Fetch Data
6.
Frequently Asked Questions
6.1.
What is HQL?
6.2.
Define Hibernate Configuration File?
6.3.
Define Hibernate's Transaction object?
7.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Many To One Annotation

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

Introduction

In many-to-one mapping, various attributes are referred to as one attribute only. In the following example, each employee has just one corporate address, and that address belongs to several employees. We will use annotation to accomplish many-to-one mapping in this case.

Let’s start by learning about the persistent class.

Persistent Classes For One-to-One Mapping

Persistent Classes: 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.

Employee.java and Address.java are two persistent classes in our one-to-one mapping hibernate project. Employee class includes a reference to Address class and vice versa.

Employee.java

package com.codingninjas;  
import javax.persistence.*;  
  
@Entity  
@Table(name="employee")  
public class Employee 
{    
     @Id  
     @GeneratedValue(strategy=GenerationType.AUTO)    
     private int emp_Id;    
    private String emp_name,emp_email;    
    @ManyToOne(cascade=CascadeType.ALL)  
    private Address emp_address;  
    public int getemp_Id() 
    {  
        return emp_Id;  
    }  
    public void setemp_Id(int em_Id) 
    {  
        this.emp_Id=emp_Id;  
    }  
    public String getemp_name() 
    {  
        return emp_name;  
    }  
    public void setemp_name(String emp_name) 
    {  
        this.emp_name=emp_name;  
    }  
    public String getemp_email() 
    {  
        return emp_email;  
    }  
    public void setemp_email(String emp_email) 
    {  
        this.emp_email=emp_email;  
    }  
    public Address getemp_address() 
    {  
        return emp_address;  
    }  
    public void setemp_address(Address emp_address) 
    {  
        this.emp_address=emp_address;  
    }    
}  
You can also try this code with Online Java Compiler
Run Code

 

Address.java

package com.codingninjas;  
  
import javax.persistence.*;  
  
@Entity  
@Table(name="address")  
public class Address 
{  
    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
    private int address_Id;    
    private String add_Line1,add_city,add_state,add_country;    
    private int add_pincode;    
   @OneToOne(cascade=CascadeType.ALL)  
    private Employee employee;  
    public int getaddress_Id() 
    {  
        return address_Id;  
    }  
    public void setaddress_Id(int address_Id) 
    {  
        this.address_Id=address_Id;  
    }  
    public String getadd_Line() 
    {  
        return add_Line;  
    }  
    public void setadd_Line(String add_Line) 
    {  
        this.add_Line=add_Line;  
    }  
    public String getadd_city() 
    {  
        return add_city;  
    }  
    public void setadd_city(String add_city) 
    {  
        this.add_city=add_city;  
    }  
    public String getadd_state() 
    {  
        return add_state;  
    }  
    public void setadd_state(String add_state) 
    {  
        this.add_state=add_state;  
    }  
    public String getadd_country() 
    {  
        return add_country;  
    }  
    public void setadd_country(String add_country) 
    {  
        this.add_country=add_country;  
    }  
    public int getadd_pincode() {  
        return add_pincode;  
    }  
    public void setadd_pincode(int add_pincode) 
    {  
        this.add_pincode=add_pincode;  
    }  
    public Employee getemployee() 
    {  
        return employee;  
    }  
    public void setemployee(Employee employee) 
    {  
        this.employee=employee;  
    }    
}  
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 that is built on a common 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. Now, insert the dependencies listed below between the dependencies>..../dependencies> tags. These dependencies are used in Maven projects to add .jar files.

<dependency>    
    <groupId>org.hibernate</groupId>    
    <artifactId>hibernate-core</artifactId>    
    <version>5.3.1.Final</version>    
</dependency> 


   
<dependency>    
    <groupId>com.oracle</groupId>    
    <artifactId>ojdbc14</artifactId>    
    <version>10.2.0.4.0</version>    
</dependency>    

Configuration File

This file provides database and mapping file information.

hibernate.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 class="com.codingninjas.Address"/>    
    <mapping class="com.codingninjas.Employee"/>    
    </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 respectively.

Store.java

package com.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=newStandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); 
		//hibernate metadata 
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
          
        Transaction t=session.beginTransaction();    
            
        Employee emp1=new Employee();    
        emp1.setemp_name("abc def");    
        emp1.setemp_email("acbc@gmail.com");    
          
        Employee emp2=new Employee();  
        e2.setemp_name("klm nop");  
        e2.setemp_email("klm@gmail.com");  
            
        Address add1=new Address();    
        add1.setadd_Line("Copernicus, Mars");    
        add1.setadd_city("Martian City");    
        add1.setadd_state("Marstate");    
        add1.setadd_country("Marsita");    
        add1.setadd_pincode(909081);    
            
        emp1.setemp_address(add1);    
        emp2.setemp_address(add1);  
      
        session.persist(emp1);    
        session.persist(emp2);  
        t.commit();    
            
        session.close();    
        System.out.println("Done");    
    }    
}   
You can also try this code with Online Java Compiler
Run Code

 

Output 

Output

Fetch.java

package com.codingninjas;    
import java.util.Iterator;     
import java.util.List;  
  
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=newStandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); 
    //hibernate metadata 
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
            
        TypedQuery query=session.createQuery("from Employee e");    
        List<Employee> list=query.getResultList();   
            
        Iterator<Employee> itr=list.iterator();    
        while(itr.hasNext()){    
         Employee emp=itr.next();    
         System.out.println(emp.getemployee_Id()+" "+emp.getemp_name()+" "+emp.getemp_email());    
         Address address=emp.getaddress_Id();    
         System.out.println(address.getadd_Line()+" "+address.getadd_city()+" "+    
            address.getadd_state()+" "+address.getadd_country()+" "+address.getadd_pincode());    
        }    
        
        session.close();    
        System.out.println("success");    
    }    
}    
You can also try this code with Online Java Compiler
Run Code


Output

1 abc def abc@gmail.com 
Copernicus, Mars Martian City Marstate Mars 909081


3 klm nop klm@gmail.com 
Copernicus, Mars Martian City Marstate Mars 909081

Frequently Asked Questions

What is HQL?

Hibernate Query Language (HQL) is a database-independent, object-oriented programming language. It's similar to SQL, only it utilizes objects instead of table names. HQL is a query language that allows you to perform a variety of actions on a relational database without resorting to complex database queries.

Define Hibernate Configuration File?

Hibernate Configuration Files are used to initialize SessionFactory and include largely database-specific settings. The Hibernate Configuration File must provide dialect information so that Hibernate understands the database type, as well as mapping file or class metadata.

Define Hibernate's Transaction object?

Transactions represent a unit of work with the database, and they are supported by the majority of RDBMS. Hibernate's transactions are managed by an underlying transaction manager, which accepts JDBC or JTA transactions.

Conclusion 

This article extensively discusses the topic Many to One Annotation in depth. It covers its introduction, and the code involved..  To hold a tighter grip on the topic, we recommend reading more blogs related to it like : Hibernate ConfigurationHibernate annotationsOne To One AnnotationOne To Many Annotation and Many to Many Annotations.

We hope that this blog has helped you enhance your knowledge regarding the topic discussed, 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