This tutorial walks you through the process of creating a RESTful API Example with Spring Boot, Spring Data REST, Spring Data JPA and Hibernate Many 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
│       │               │   ├── Author.java
│       │               │   └── Book.java
│       │               └── repository
│       │                   ├── AuthorRepository.java
│       │                   └── BookRepository.java
│       └── resources
│           └── application.properties
└── pom.xml

Project dependencies


Define JPA Entities and Repositories

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 book

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

Create a new author

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

Assign the author to the book

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

Source code

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

See also

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