Hibernate - One-to-Many Mapping - GeeksforGeeks

27 Dec, 2021
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence api) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernating. In this article, we will discuss One-to-Many Mapping in the Hibernate. Let’ understand the One to many mapping with the help of a real-life example. Bike manufacture can manufacture multiple models of the bike but the same bike model cannot be manufactured by multiple manufactures.
Syntax:
@oneToMany(mappedby=”nameofmappedvariable”) 
This mappedvariable of the other tables is responsible for mapping between two tables.
Spring Initializer is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer.
Step 1: Go to this link. Fill in the details as per the requirements. For this application:
Project: Maven
Language: Java
Spring Boot: 2.5.7
Packaging: JAR
Java: 11
Dependencies: Spring Web,Spring Data JPA, MySql Driver
Click on Generate which will download the starter project.
Step 2: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:
Project Structure:
One to Many Mapping
Step 3: Adding the necessary properties in the application.properties file. (mapping is the database name)
spring.datasource.username=root
spring.datasource.password=Aayush
spring.datasource.url=jdbc:mysql://localhost:3306/mapping
spring.jpa.hibernate.ddl-auto=update
Step 4: Go to src->main->java->com->example->Mapping and create two  files in the models folder i.e Manufactures.java  and  Model.java
Project structure:
Manufactures.java
Java
package com.example.Mapping.Models; import javax.persistence.*;import java.util.List; @Entitypublic class Manufactures {       @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private int id;        // One manufactures can produces    // multiple models of the bike    private  String manufactures_name;     @OneToMany(mappedBy ="ob")     private List<Model>models;     public Manufactures(int id, String manufactures_name) {        this.id = id;        this.manufactures_name = manufactures_name;    }       Manufactures(){     }     public int getId() {        return id;    }     public void setId(int id) {        this.id = id;    }     public String getManufactures_name() {        return manufactures_name;    }     public void setManufactures_name(String manufactures_name) {        this.manufactures_name = manufactures_name;    }}
Models(Mapped by table)
Java
package com.example.Mapping.Models; import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne; @Entitypublic class Model {       @Id    private int model_id;     private String name;     @ManyToOne    @JoinColumn(name = "manufacture_id")    private Manufactures ob;     public Model(int model_id, String name, Manufactures ob) {        this.model_id = model_id;        this.name = name;        this.ob = ob;    }       Model(){     }     public int getModel_id() {        return model_id;    }     public void setModel_id(int model_id) {        this.model_id = model_id;    }     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public Manufactures getOb() {        return ob;    }     public void setOb(Manufactures ob) {        this.ob = ob;    }}
Step 5: Adding the JPA repository of both classes in the project structure:
ManufactureRepo
Java
package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Manufactures;import org.springframework.data.jpa.repository.JpaRepository; public interface ManufacturesRepo extends JpaRepository<Manufactures,Integer> {   }
ModelRepo:
Java
package com.example.Mapping.Reposteries; import com.example.Mapping.Models.Model;import org.springframework.data.jpa.repository.JpaRepository; public interface ModelRepo extends JpaRepository<Model, Integer> {}
MappingApplication:
Java
package com.example.Mapping; import com.example.Mapping.Models.Manufactures;import com.example.Mapping.Models.Model;import com.example.Mapping.Reposteries.ManufacturesRepo;import com.example.Mapping.Reposteries.ModelRepo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplicationpublic class MappingApplication implements CommandLineRunner {     @Autowired    ManufacturesRepo manufacturesRepo;       @Autowired    ModelRepo modelRepo;     public static void main(String[] args) {        SpringApplication.run(MappingApplication.class, args);    }         @Override    public void run(String... args) throws Exception {         Manufactures data=new Manufactures(1,"Honda");        // Inserting the record in the Manufactures table.    manufacturesRepo.save(data);            // Now try to mapped above record with multiple models        Model model1=new Model(1,"AYZ",data);        Model model2=new Model(2,"ZET",data);        modelRepo.save(model1);        modelRepo.save(model2);     }}
Run the main application:
manufacture table
model table
varshagumber28
rajeev0719singh
Java-Hibernate
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Introduction to Java
Difference between Abstract Class and Interface in Java