One to Many Mapping Hibernate/JPA Using Spring Boot and MySQL

Spring Boot is a powerful new framework for building both Java and non-Java applications. One of the cool features of Spring Boot is that it allows developers to avoid the overhead of configuring an application in a development environment, and instead relies on a single classpath across all application containers, which makes it very easy to build applications that can be deployed in multiple environments without any changes. In this post I will show you how to easily build a Spring Boot application that uses Hibernate/JPA to handle relational data.

Recently, our team has been working on Spring Boot and JPA based application, which is mostly used for database management, data access and database mapping. In this blog, we are going to give steps to implement Spring Boot Hibernate One to Many mapping example through command line.

In a previous post, we have described how to write a Spring MVC application with Hibernate and JPA. But, what if you need to persist the objects you have created? After all, in most MVC applications, you end up with lots of objects, and it is not uncommon to require several objects to be persisted into the database.

In this article, I’ll show you how to utilize Hibernate/Spring Data JPA to create One-to-Many Mapping in your Spring Boot application. I’ll utilize a MySQL server as a database.

I’ll use two JPA entities to illustrate how the one-to-many connection works: a Book and a Story. Numerous tales may be connected with one book, and one book can contain many stories. This is referred to as a “one-to-many” connection.

Let’s have a look at a few things first.

Two JPA entities will be implemented: and The Book and Story entities will have bidirectional One to Many and Many to One relationships.

For the sake of this example, I’m assuming that one book may include many tales and that multiple stories can be linked with one book. I’m going to use two annotations in my code to make it work: @OneToMany and @ManyToOne.

We shall not be building any database tables ourselves when it comes to database tables. Because I’m using Spring Data JPA, the framework will generate all database tables depending on how the JPA object is annotated. As a result, pay close attention to the annotations.

Fetch Types by Default

We’ll need two specific annotations to build the one-to-many relationship: @OneToMany and @ManyToOne. There is a default fetch type for these and other related annotations. I believe it is necessary to provide their default settings here.

@OneToOne – EAGER is the default fetch type. LAZY is the default fetch type for @OneToMany. @ManyToOne – EAGER is the default fetch type. LAZY is the default fetch type for @ManyToMany.

Spring Boot, Maven, Embedded Tomcat, Postman, Eclipse, and the MySQL database will be used.

Spring Boot One-to-Many Mapping in Hibernate/JPA

Open pom.xml in a new maven project and replace the code with the following.

2.5.3 com.onetoonehibernatejpa 4.0.0 org.springframework.boot spring-boot-starter-parent onetoone war onetoone 0.0.1-SNAPSHOT Spring Boot demo project 1.8 org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime true org.springframework.boot spring-boot-starter-tomcat supplied org.springframework.boot spring-boot-maven-plugin mysql-connector-java runtime

Let maven download all necessary jars. Once it is done you will be able to see the maven dependency folder which contains different jar files. You can start writing our controller classes, ServiceImpl and Repository. The directory structure of the application looks as below.


The JPA Entity in the Book

package com.onetoonehibernatejpa.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = “book”) public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int bookId; @Column(name = “book_name”) private String bookName; @OneToMany(fetch = FetchType.EAGER, mappedBy = “book”, cascade = CascadeType.ALL) @JsonIgnoreProperties(“book”) private List storyList = new ArrayList<>(); public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public List getStoryList() { return storyList; } public void setStoryList(List storyList) { this.storyList = storyList; } }

The JPA Entity Story

package com.onetoonehibernatejpa.entity; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = “story”) public class Story { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int storyId; @Column(name = “story_name”) private String storyName; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = “book_id”, referencedColumnName = “bookId”) @JsonIgnoreProperties(“storyList”) private Book book; public int getStoryId() { return storyId; } public void setStoryId(int storyId) { this.storyId = storyId; } public String getStoryName() { return storyName; } public void setStoryName(String storyName) { this.storyName = storyName; } public Book getBook() { return book; } public void setBook(Book book) { = book; } }

Extend JpaRepository with a Repository Interface.

The BookRepository is an online library of books.

package com.onetoonehibernatejpa.repository; import; import org.springframework.stereotype.Repository; import com.onetoonehibernatejpa.entity.Book; @Repository public interface BookRepository extends JpaRepository<Book, String> { public Book findByBookId(int bookId); }

Create a user interface for a service.

The BookService is a service that allows you to order books

@Component public interface; package com.onetoonehibernatejpa.service; import org.springframework.stereotype.Component; import com.onetoonehibernatejpa.entity.Book; public Book saveBook(Book book); public Book findByBookId(int bookId); public Book findByBookId(int bookId); public Book findByBookId(int bookId); public Book findByBookId(int book

The StoryRepository is a collection of stories. Repository for JPA

package com.onetoonehibernatejpa.repository; import; import org.springframework.stereotype.Repository; import com.onetoonehibernatejpa.entity.Story; @Repository public interface StoryRepository extends JpaRepository<Story, String> { }

Service Implementation Class should be defined.

The Java Class BookServiceImpl

package com.onetoonehibernatejpa.service.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.onetoonehibernatejpa.entity.Book; import com.onetoonehibernatejpa.entity.Story; import com.onetoonehibernatejpa.repository.BookRepository; import com.onetoonehibernatejpa.service.BookService; @Service public class BookServiceImpl implements BookService { @Autowired private BookRepository bookRepository; public Book saveBook(Book book) { List storyList = new ArrayList<>(); // create first story Story story1 = new Story(); story1.setStoryName(“Arrays”); // create second story Story story2 = new Story(); story2.setStoryName(“Pointers”); // create third story Story story3 = new Story(); story3.setStoryName(“Loops”); // add all story into storyList. Till here we have prepared data for OneToMany storyList.add(story1); storyList.add(story2); storyList.add(story3); // Prepare data for ManyToOne story1.setBook(book); story2.setBook(book); story3.setBook(book); book.setStoryList(storyList); book =; return book; } public Book findByBookId(int bookId) { Book book = bookRepository.findByBookId(bookId); return book; } }

The BookController is a program that allows you to manage your books

package com.onetoonehibernatejpa.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.onetoonehibernatejpa.entity.Book; import com.onetoonehibernatejpa.service.BookService; @RestController @RequestMapping(value = “/book”) public class BookController { @Autowired private BookService bookService; @RequestMapping(value = “/savebook”, method = RequestMethod.POST) @ResponseBody public Book saveBook(@RequestBody Book book) { Book bookResponse = bookService.saveBook(book); return bookResponse; } @RequestMapping(value = “/{bookId}”, method = RequestMethod.GET) @ResponseBody public Book getBookDetails(@PathVariable int bookId) { Book bookResponse = bookService.findByBookId(bookId); return bookResponse; } } is a Java class that controls a story.

import java.util; package com.onetoonehibernatejpa.controller Import org.springframework.beans.factory.annotation into the list. Import org.springframework.web.bind.annotation; autowired Import org.springframework.web.bind.annotation for RequestMapping. Import org.springframework.web.bind.annotation into ResponseBody. Import com.onetoonehibernatejpa.entity.Story; import com.onetoonehibernatejpa.repository; RestController @RestController @RequestMapping(value = “/story”) public class StoryRepository @Autowired StoryController public List getBookDetails() public List storyresponse = (List) storyRepository.findAll(); return storyresponse; @RequestMapping(value = “/stories”) @RequestMapping(value = “/stories”) @RequestMapping(value = “/stories”) @RequestMapping(value = “/stories”) @RequestMapping(value = “/stories”) @RequestMapping(value = “/stories

Finally, you have an file with database information.

characteristics of the application

spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:mysql:/localhost:3306/db test [email protected] spring.datasource.username=test true spring.datasource.driver-class-name =com.mysql.jdbc.Driver

Let’s start our program and check out the endpoints.







Information about the database



That concludes our discussion on Hibernate/JPA One-to-Many Mapping with Spring Boot and MySQL.

Mapping over one to many relationships is a common requirement when working with collections of similar objects. For example, in order to store a User object with multiple User objects in a collection, we would typically have a one to many relationship between our User model and an ArrayList of the User objects. To map the relationship, we would usually use the Hibernate ORM, since it can automatically detect the one to many mapping.. Read more about jpa repository one-to-many query example and let us know what you think.

This article broadly covered the following related topics:

  • spring boot jpa one-to-many-example github
  • spring boot crud example using one-to-many mapping
  • spring boot jpa one to many example rest api
  • how to fetch data in one-to-many relationship in jpa
  • jpa repository one-to-many query example
You May Also Like