Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Implement One to Many Mapping in Spring Boot?
Next article icon

How to Implement One to Many Mapping in Spring Boot?

Last Updated : 02 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 hibernate. In this article, we will discuss how to insert the values in the MySQL table using Spring JPA. Spring Initializr 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 by Step Implementation

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.6 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:

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 Address.java and Student Information.java.

Project structure:

Address.java(Mapped table)

Java
package com.example.Mapping.Models;  import javax.persistence.*;  @Entity // Adding the table name @Table(name = "Address") public class Address {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id;     private String cityname;        // Mapping the column of this table      @ManyToOne     //Adding the name     @JoinColumn(name = "Student_id")     StudentInformation ob;      Address() {}      public Address(int id, String cityname, StudentInformation ob1)     {         this.id = id;         this.cityname = cityname;         this.ob = ob1;     } } 

StudentInformation.java(Mapped by table)

Java
@Entity // Adding the table name @Table(name = "Student") public class StudentInformation {     @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int rollno;     private String name;        // Mapping to the other table     @OneToMany(cascade = CascadeType.ALL)     private Set<Address> ob;     public int getRollno() { return rollno; }      public StudentInformation() {}      public StudentInformation(int rollno, String name)     {         this.rollno = rollno;         this.name = name;     }      public void setRollno(int rollno)     {          this.rollno = rollno;     }      public String getName() { return name; }      public void setName(String name) { this.name = name; } } 

Step 5: Adding the JPA repository of both classes in the project structure:

Project Structure:

AddressRepo:

Java
package com.example.Mapping.Repository;  import com.example.Mapping.Models.Address; import org.springframework.data.jpa.repository.JpaRepository;  public interface AddressRepo extends JpaRepository<Address, Integer> {  } 

StudentRepo:

Java
package com.example.Mapping.Repository;  import com.example.Mapping.Models.StudentInformation; import org.springframework.data.jpa.repository.JpaRepository;  public interface StudentRepo extends JpaRepository<StudentInformation, Integer> { } 

Step 6: Executing the information in these tables

MappingApplication:

Java
@SpringBootApplication public class MappingApplication implements CommandLineRunner {      @Autowired StudentRepo ob;     @Autowired AddressRepo ob1;     public static void main(String[] args)     {         SpringApplication.run(MappingApplication.class, args);     }      @Override     public void run(String... args) throws Exception     {         StudentInformation student = new StudentInformation(1, "Aayush");         ob.save(student);         Address address = new Address(1, "Sonipat", student);         ob1.save(address);     } } 

Now run the main application

Terminal Output:

StudentTable:

Address.java


Next Article
How to Implement One to Many Mapping in Spring Boot?

Z

zack_aayush
Improve
Article Tags :
  • Java
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Difference Between @Service Annotation and @Repository Annotation
    Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.  @Service Annota
    7 min read
    Unit Testing in Spring Boot Project using Mockito and Junit
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    6 min read
    Spring Boot - Thymeleaf with Example
    Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI. The engine allows a parallel work of the backend and
    6 min read
    Spring Boot - MongoRepository with Example
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    5 min read
    Spring Boot - Integrating Hibernate and JPA
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
    Spring Boot JpaRepository with Example
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    9 min read
    Spring Boot - CRUD Operations using MongoDB
    CRUD stands for Create, Read/Retrieve, Update, and Delete and these are the four basic operations that we perform on persistence storage. CRUD is data-oriented and the standardized use of HTTP methods. HTTP has a few methods which work as CRUD operations and do note they are very vital from a develo
    5 min read
    Spring Boot - Spring Data JPA
    Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we must know about ORM (Object Relation Mapping). So Object relation mapping is simply the process of persisting any java object directly into a database table. Usually, the name of the object being persisted become
    6 min read
    Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    8 min read
    Spring Boot - Difference Between CrudRepository and JpaRepository
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences