Spring Data Rest – How to create a RestAPIs with JPA One-to-Many relational entities | SpringBoot + MySql + HAL Browser

In the tutorial, JavaSampleApproach will guide how to build a Spring Data Rest application for Jpa One-To-Many relational entities with SpringBoot.

Related posts:
Spring Data Rest – How to create a RestAPIs with JPA Many-to-Many relational entities | SpringBoot + MySql + HAL Browser
How to access MySQL database with Spring Data Rest application
How to configure Spring JPA One to Many Relationship – SpringBoot

I. Technology

– Java 8
– Maven 3.6.1
– Spring Tool Suite: Version 3.8.4.RELEASE
– Spring Boot: 1.5.4.RELEASE
– MySQL
– Hal Browser

II. Practice

The tutorial creates a SpringBoot project with 2 Jpa entities {Company, Product} which have One-to-Many relationship. We use Spring Data Rest to build restfulAPIs for accessing MySQL data which are created by 2 entities. Then using HalBrowser to consume the rests.

Step to do:
– Create SpringBoot project
– Create Jpa entities
– Create Rest repositories
– Implement CommandLineRunner client
– Run and check results

spring data rest - jpa one-to-many entities - project structure

1. Create SpringBoot project

Using SpringToolSuite to create a SpringBoot project. Then add dependencies:

2. Create Jpa entities

Create 2 Jpa entities with One-to-Many relationship {Company, Product}:

– Company

– Product

3. Create Rest repositories

Create 2 rest repositories {CompanyRepository, ProductRepository}:

– CompanyRepository

– ProductRepository

– Open application.properties file, configure spring.datasource:

4. Implement CommandLineRunner client

In main class, we use CommandLineRunner to init Company and Product objects, then using CompanyRepository to store them in MySql database.

5. Run and check results

Build and Run the SpringBoot project with commandlines {mvn clean install, mvn spring-boot:run}.
The SpringBoot application creates 2 tables {company, product}:

spring data rest - jpa one-to-many entities - company-product tables

– Make a request http://localhost:8080:

spring data rest - jpa one-to-many entities - first request

– Select all companies:

spring data rest - jpa one-to-many entities - select all company

– Select all products:

spring data rest - jpa one-to-many entities - all products

– Select products of a company:

spring data rest - jpa one-to-many entities - products of a company

– Select company of a product:

spring data rest - jpa one-to-many entities - company of a product

III. Sourcecode

SpringRestDataOneToMany


Related Posts


1 thought on “Spring Data Rest – How to create a RestAPIs with JPA One-to-Many relational entities | SpringBoot + MySql + HAL Browser”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*