Open In App

Hibernate – Many-to-One Mapping

Improve
Improve
Like Article
Like
Save
Share
Report

Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and with a server also. It is a top layer of JDBC, JTA, and JNDI Technologies. It follows the ORM concept

  • ORM is a theoretical concept 
  • It makes programming or development is in the object orientation process

Hibernate supports object-orientation programming by using the mapping concepts. This mapping should be done by the programmer then hibernate will insert the objects into the Database table as a row and the row can be converted back to an object without any SQL query written by the programmer 

Associations in Hibernate

Parent class must have child class reference with or without collection type. This association can also follow multiplicity as

  • One-To-One
  • One-To-Many
  • Many-To-One
  • Many-To-Many

Here these are divided into two types they are 

Non-collection type:

  • One-To-One
  • Many-To-One

Collection Type:

  • One-To-Many
  • Many-To-Many

Here we are going to discuss Many-To-One mapping developed by using  SpringBoot Data JPA in STS (Spring Tool Suite)

Spring Boot

SpringBoot is an extension of the spring-based framework which eliminates the boilerplate configuration required for the setup spring-based application. It is basically built on top of the spring framework to basically reduce a lot of configuration required to set up a spring-based application. The main purpose of SpringBoot is to reduce the common code written by programmers which is called Autoconfiguration. Data JPA provides @NoRepositoryBean which is autoconfigured and self logic implemented for basic operations. In simply JPA (Java Persistence API) is an interface Hibernate provides the implementation for the interface methods

Many-To-One Mapping

In this article, we will discuss Many-To-One mapping with help of one example. Many employees work in the same company so all the working employees have the same company address. Many employees have one address

Java




// Syntax
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "Foreign key column")


Steps To Creating Spring Boot Project Using STS

Step 1: Open the STS (Spring Tool Suite)

Step 2: Click on the File menu –>select New–>select Spring Starter Project then a new window is opened that provides the required details like Name, Group, Artifact, java version, etc.

Creating Spring Boot Project Using STS

 

Creating Spring Boot Project Using STS

 

Step 3: Enter Project name, Enter Artifact, Group, then click on–>Next–>then another new window will be open in that you will provide SpringBoot Version and required dependencies for this project (Spring Data Jpa and MySql Driver ) dependencies are required add these dependencies then click on–>finish. 

Add Dependency

 

Then project is created in the editor name as GFG-MAPPING-PROJECT The project Structure looks like as below.

Project Structure

 

Step 4:

Go to src/main/resources open application.properties in that adding the necessary properties as below

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/schemaname
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Step 5:

Go to src/main/java create a package for model classes(ex : com.gfg.model) and create one package for repository  (ex :com.gfg.repository). Then create two model classes under the model package

  • Employee.java
  • Address.java

Employee.java

Java




package com.gfg.model;
 
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
 
@Entity
public class Employee {
 
    @Id private int empId;
    private String empName;
   
    // Many employees has one company address
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address_id")
    private Address address;
 
    public Employee(int empId, String empName,
                    Address address)
    {
        super();
        this.empId = empId;
        this.empName = empName;
        this.address = address;
    }
 
    public Employee() { super(); }
 
    @Override public String toString()
    {
        return "Employee []";
    }
 
    public int getEmpId() { return empId; }
 
    public void setEmpId(int empId) { this.empId = empId; }
 
    public String getEmpName() { return empName; }
 
    public void setEmpName(String empName)
    {
        this.empName = empName;
    }
 
    public Address getAddress() { return address; }
 
    public void setAddress(Address address)
    {
        this.address = address;
    }
}


Address.java

Java




package com.gfg.model;
 
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
 
@Entity
public class Address {
 
    @Id private int addressId;
    private String location;
 
    @OneToMany(cascade = CascadeType.ALL,
               mappedBy = "address")
    private List<Employee> employee
        = new ArrayList<>();
 
    public Address(int addressId, String location)
    {
        super();
        this.addressId = addressId;
        this.location = location;
    }
 
    public Address() { super(); }
 
    public int getAddressId() { return addressId; }
 
    public void setAddressId(int addressId)
    {
        this.addressId = addressId;
    }
 
    public String getLocation() { return location; }
 
    public void setLocation(String location)
    {
        this.location = location;
    }
 
    public List<Employee> getEmployee() { return employee; }
 
    public void setEmployee(List<Employee> employee)
    {
        this.employee = employee;
    }
}


Step 6:

Go to repository package adding the JPA repository of both model  classes 

EmployeeRepo.java

Java




package com.gfg.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import com.gfg.model.Employee;
 
public interface EmployeeRepo extends JpaRepository<Employee,Integer>{
 
}


 AddressRepo.java

Java




package com.gfg.repository;
 
import org.springframework.data.jpa.repository.JpaRepository;
import com.gfg.model.Address;
 
public interface AddressRepo extends JpaRepository<Address,Integer>{
 
}


Step 7: Go to starter class Autowire two repository interfaces and create objects for model classes 

GfgMappingProjectApplication.java

Java




package com.gfg;
 
import com.gfg.model.Address;
import com.gfg.model.Employee;
import com.gfg.repository.AddressRepo;
import com.gfg.repository.EmployeeRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class GfgMappingProjectApplication
    implements CommandLineRunner {
 
    @Autowired AddressRepo addessRepo;
    @Autowired EmployeeRepo empRepo;
 
    public static void main(String[] args)
    {
        SpringApplication.run(
            GfgMappingProjectApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception
    {
 
        Address addr = new Address(1, "Bangloor");
        addessRepo.save(addr);
 
        Employee emp1 = new Employee(1, "Alpha", addr);
        Employee emp2 = new Employee(2, "Beeta", addr);
 
        empRepo.save(emp1);
        empRepo.save(emp2);
    }
}


Step 8: Run the Main Application

Right-click on GfgMappingProjectApplication select  Run as spring boot application

Output

 

Then go to Database then check for tables. 

Address Table:

select * from address;
Output

 

Employee Table:

select * from employee;
Output

 



Last Updated : 13 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads