This post walks you through the process of creating a RESTful API Example with Spring Data REST, Spring Data JPA Many To Many Extra Columns 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

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── restfulapi
│       │               ├── Application.java
│       │               ├── model
│       │               │   ├── Book.java
│       │               │   ├── BookPublisher.java
│       │               │   └── Publisher.java
│       │               └── repository
│       │                   ├── BookPublisherRepository.java
│       │                   ├── BookRepository.java
│       │                   └── PublisherRepository.java
│       └── resources
│           └── application.properties
└── pom.xml

Project dependencies


Create database

Create a new empty MySQL database named restful_api. Tables will be auto created by Hibernate when the application started

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




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 "{\"name\" : \"Book 1\"}" http://localhost:8080/books  

Create a new publisher

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

Link the book with the publisher

curl -i -X POST -H "Content-Type:application/json" -d "{\"book\" : \"http://localhost:8080/books/1\", \"publisher\" : \"http://localhost:8080/publishers/1\", \"publishedDate\": \"2017-01-01\"}" http://localhost:8080/bookPublishers  

Source code

[email protected]:hellokoding/restfulapi-springdatarest-manytomany-extracolumns-mysql.git

https://github.com/hellokoding/restfulapi-springdatarest-manytomany-extracolumns-mysql