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 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

Init project strucure

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


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 "{\"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

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

See also

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