In this tutorial, we will learn how to use Hibernate and JPA with Spring Boot. We’ll also learn how to create a simple application that uses MySQL as the database backend.
The spring boot jpa one-to-many-example github is a blog post that explains how to map a One to Many relationship using Spring Boot and MySQL.
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: Book.java and Story.java. 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
Allow Maven to download all required jars. You’ll be able to view the maven dependency folder, which includes several jar files, after it’s finished. You may begin creating our ServiceImpl and Repository controller classes. The application’s directory structure is as follows.
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; @Id @GeneratedValue(strategy = GenerationType.AUTO) public class Book @Column(name = “book name”); private int bookId @OneToMany(fetch = FetchType.EAGER, mappedBy = “book”, cascade = CascadeType.ALL); private String bookName; @OneToMany(fetch = FetchType.EAGER, mappedBy = “book”, cascade = CascadeType.ALL) @JsonIgnoreProperties(“book”) public int getBookId() return bookId; private List storyList = new ArrayList>(); this.bookId = bookId; public void setBookId(int bookId); return bookName from public String getBookName(); this.bookName = bookName; public void setBookName(String bookName); return storyList from public List getStoryList(); setStoryList(List storyList) public void 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.per @Table(name = “story”) @Entity @Id @GeneratedValue(strategy = GenerationType.AUTO) public class Story @Column(name = “story name”); private int storyId @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER); private String storyName; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = “book id”, referencedColumnName = “bookId”) @JoinColumn(name = “book id”, referencedColumnName = “bookId”) @JoinColumn @JsonIgnoreProperties(“storyList”) public int getStoryId() return storyId; private Book book; public int getStoryId() return storyId; this.storyId = storyId; public void setStoryId(int storyId); return storyName from public String getStoryName(); this.storyName = storyName; public void setStoryName(String storyName); return book; public Book getBook(); setBook(Book book) public void this.book = book;
Extend JpaRepository with a Repository Interface.
The BookRepository is an online library of books.
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.onetoonehibernatejpa.entity.Book; @Repository public interface; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework. public Book findByBookId(int bookId); public Book findByBookId(int bookId); public Book findByBookId(int bookId); public Book findByBookId(int bookId); 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
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.onetoonehibernatejpa.entity.Story; @Repository public interface package com.onetoonehibernatejpa.entity.Story; @Repository public interface package com.onetoonehibernatejpa.entity.S JpaRepositoryStory, String> is an extension of StoryRepository.
Service Implementation Class should be defined.
The Java Class BookServiceImpl
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.onetoonehibernatejpa.entity.Book; import com.onetoonehibernatejpa.repository.BookRepository; import com.onetoonehibernatejpa.entity.Story; import com.onetoonehibern @Autowired private BookRepository bookRepository; public Book saveBook; BookServiceImpl implements BookService (Book book) storyList = new ArrayList> List storyList = new ArrayList> () ; / make your first tale story1 = new Story(); story2 = new Story(); story3 = new Story(); story4 = new setStoryName(“Arrays”); / start a new narrative Story story2 = new Story(); story2.setStoryName(“Pointers”); story3 = new Story(); story4 = new Story(); story5 = new Story(); story6 = new 3.setStoryName(“Loops”); / populate storyList with all stories. We’ve prepared data for OneToMany storyList.add(story1); storyList.add(story2); storyList.add(story3); / Prepare data for ManyToOne storyList.add(story1); storyList.add(story2); storyList.add(story3); tale; 1.setBook(book); tale; 2.setBook(book); 3.setBook(book); book.setStoryList(storyList); book = bookRepository.save(book); return book; public Book findByBookId(int bookId) Book book = bookRepository.findByBookId(bookId); 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
import org.springframework.beans.factory.annotation; package com.onetoonehibernatejpa.controller Import org.springframework.web.bind.annotation; autowired Import org.springframework.web.bind.annotation as a PathVariable. Import org.springframework.web.bind.annotation into RequestBody. Import org.springframework.web.bind.annotation for RequestMapping. Import org.springframework.web.bind.annotation into RequestMethod. Import org.springframework.web.bind.annotation into ResponseBody. Import com.onetoonehibernatejpa.entity into RestController. @RestController @RequestMapping(value = “/book”) public class; import com.onetoonehibernatejpa.service.BookService; @RestController @RequestMapping(value = “/book”) public class @RequestMapping(value = “/savebook”, method = RequestMethod.POST) @ResponseBody public Book saveBook(@RequestBody Book book) Book bookResponse = bookService.saveBook(book); return bookResponse; @Autowired private BookService bookService; @RequestMapping(value = “/savebook”, method = RequestMethod.POST) @RequestB @ResponseBody public Book getBookDetails(@PathVariable int bookId) @RequestMapping(value = “/bookId”, method = RequestMethod.GET) @ResponseBody public Book bookResponse = bookService.findByBookId(bookId); return bookResponse;
StoryController.java 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 application.properties 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 #spring.jpa.show-sql: true spring.datasource.driver-class-name =com.mysql.jdbc.Driver
Let’s start our program and check out the endpoints.
http://localhost:8080/book/savebook
http://localhost:8080/story/stories
http://localhost:8080/book/1
Information about the database
That concludes our discussion on Hibernate/JPA One-to-Many Mapping with Spring Boot and MySQL.
The how to fetch data in one-to-many relationship in jpa is a blog post that explains how to use Spring Boot and MySQL for One to Many mapping.
Related Tags
- spring boot crud example using one-to-many mapping
- one to many mapping in spring boot jpa example
- spring boot jpa one to many example rest api
- spring data jpa one-to-many unidirectional example
- spring boot one to many mapping example