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

In the tutorial, JavaSampleApproach will show you 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:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

2. Create Jpa entities

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

– Company


package com.javasampleapproach.restdata.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Company {
	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
    private String name;
    
    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set products;
    
    public Company(){
    }
    
    public Company(String name){
    	this.name = name;
    }
    
    public Company(String name, Set products){
    	this.name = name;
    	this.products = products;
    }
    
    // name
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    // products
    public void setProducts(Set products){
    	this.products = products;
    }
    
    public Set getProducts(){
    	return this.products;
    }
}

– Product


package com.javasampleapproach.restdata.model;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Product {
	
	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
    private String name;
    
    @ManyToOne(fetch = FetchType.EAGER)
    private Company company;
    
    public Product(){
    }
    
    public Product(String name){
    	this.name = name;
    }
    
    public Product(String name, Company company){
    	this.name = name;
    	this.company = company;
    }
    
    // name
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    // products
    public void setCompany(Company company){
    	this.company = company;
    }
    
    public Company getCompany(){
    	return this.company;
    }
}

3. Create Rest repositories

Create 2 rest repositories {CompanyRepository, ProductRepository}:

– CompanyRepository


package com.javasampleapproach.restdata.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.javasampleapproach.restdata.model.Company;

@RepositoryRestResource(collectionResourceRel = "company", path = "company")
public interface CompanyRepository extends PagingAndSortingRepository {
}

– ProductRepository


package com.javasampleapproach.restdata.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.javasampleapproach.restdata.model.Product;

@RepositoryRestResource(collectionResourceRel = "product", path = "product")
public interface ProductRepository extends PagingAndSortingRepository {
}

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


spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.generate-ddl=true

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.


package com.javasampleapproach.restdata;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.javasampleapproach.restdata.model.Company;
import com.javasampleapproach.restdata.model.Product;
import com.javasampleapproach.restdata.repository.CompanyRepository;

@SpringBootApplication
public class SpringRestDataOneToManyApplication implements CommandLineRunner{

	@Autowired
	CompanyRepository companyRepository;
	
	public static void main(String[] args) {
		SpringApplication.run(SpringRestDataOneToManyApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		/*
		 * Apple company & products
		 */
		// initial company and products 
		Product iphone7 = new Product("Iphone 7");
		Product iPadPro = new Product("IPadPro");
		
		Set appleProducts = Stream.of(iphone7, iPadPro).collect(Collectors.toSet());
		
		Company apple = new Company("Apple", appleProducts);
		
		iphone7.setCompany(apple);
		iPadPro.setCompany(apple);
		
		// send message to ActiveMQ
		companyRepository.save(apple);
        
        /*
         * Samsung company and products
         */
		Product galaxyS8 = new Product("Galaxy S8");
		Product gearS3 = new Product("Gear S3");
		
		Set samsungProducts = Stream.of(galaxyS8, gearS3).collect(Collectors.toSet());
		
		Company samsung = new Company("Samsung", samsungProducts);
		
		galaxyS8.setCompany(samsung);
		gearS3.setCompany(samsung);
		
        /*
         * send message to ActiveMQ
         */
		companyRepository.save(samsung);
	}
}

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



By grokonez | July 8, 2017.

Last updated on May 10, 2021.



Related Posts


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

  1. This is easy. The challenging part is however, how to make a POST request to insert a new record, specially in parent-child relationship entity. You missed that part.

    If you could include few examples of POST requests, that would be great.

    1. It’s impossible to create a brand new entity with association to another already existing entity via 1 POST request.
      I searched the internet, documentation, asked people – for years and no one knows how to.

  2. This is not example of spring data rest.. Its only using simpe Jpa. Kindly elaborate data rest with one to one mapping etc

  3. please show how to insert and search data in one to many mapping from postman using spring data rest coding

  4. In this example you are inserting data in hard coding but i want to insert data using postman or any other rest Client tool

Got Something To Say:

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

*