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

What you'll need

  • JDK 8+ or OpenJDK 8+
  • Maven 3+
  • MySQL Server 5+ or Docker CE 18+

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── springdatarest
│       │               ├── book
│       │               │   ├──
│       │               │   └──
│       │               └──
│       └── resources
│           └──
├── Dockerfile
├── docker-compose.yml
└── pom.xml

Project dependencies

Define JPA Entity and Repository

Define JPA Entity

Define Spring Data Repository

Spring Data Rest will auto create RESTful APIs based on domain model and repository, all you have to do in this example is to extend JpaRepository

Config and Run

Application Configurations

Run with JDK/OpenJDK, Maven and MySQL Server local

Update hk-mysql on to localhost and type the below command at the project root directory

mvn clean spring-boot:run  

Run with Docker

Prepare Dockerfile for Java/Spring Boot application and docker-compose.yml for MySQL Server

Type the below command at the project root directory, make sure your local Docker is running

docker-compose up  

Access to MySQL Server docker container by issuing below bash command and key in hellokoding on Enter password:

docker exec -it hk-mysql mysql -p

Query schema and data created by JPA/Hibernate based on your mapping

Query the data

Book data should be empty now. Let create it with the exposed RESTful APIs.

Test your RESTful APIs with curl

Create some new books

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

Find all books

curl http://localhost:8080/books

Find book with id=2

curl curl http://localhost:8080/books/2

Update book id 2

curl -i -X PATCH -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding 2 updated\"}" http://localhost:8080/books/2

Replace book id 2

curl -i -X PUT -H "Content-Type:application/json" -d "{\"title\" : \"Hello Koding 2 replaced\"}" http://localhost:8080/books/2

Delete book id 2

curl -i -X DELETE http://localhost:8080/books/2

Source code

See also

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