This tutorial will walk you through the steps of creating a RESTful API Example with Spring Boot, Spring Data REST, Spring Data JPA and Hibernate One To Many Relationship and MySQL.

What you'll need

  • JDK 1.7+
  • Maven 3+
  • MySQL Server 5.6+

Stack

  • Spring Boot
  • Spring Data REST
  • Spring Data JPA
  • MySQL

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── restfulapi
│       │               ├── Application.java
│       │               ├── model
│       │               │   ├── Book.java
│       │               │   └── BookCategory.java
│       │               └── repository
│       │                   ├── BookCategoryRepository.java
│       │                   └── BookRepository.java
│       └── resources
│           └── application.properties
└── pom.xml

Project dependencies


Define JPA Entity and Repository

Create domain objects



Spring Data Repository

Spring Data JPA and Spring Data Rest will auto create some helper methods and RESTful APIs. For this example, we only need to extend JpaRepository



Config and Run

Application Properties


Run the application


Type mvn clean spring-boot:run on terminal at the project root directory to run

Test the application

Create a new category

curl -i -X POST -H "Content-Type:application/json" -d "{\"name\":\"Cat 1\"}" http://localhost:8080/bookCategories  

Create a new book

curl -i -X POST -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding\", \"description\": \"Simple coding examples and tutorials\"}" http://localhost:8080/books  

Assign book to category

curl -i -X PUT -H "Content-Type:text/uri-list" -d "http://localhost:8080/bookCategories/1" http://localhost:8080/books/1/bookCategory  

Source code

https://github.com/hellokoding/hellokoding-courses/blob/master/springboot-examples/springdatarest-mysql-one-to-many

See also

Handling Circular Reference of JPA/Hibernate Entity Bidirectional Relationships with Jackson JsonIgnoreProperties