This tutorial will walk you through the steps of creating an example on handling circular references/dependencies of JPA/Hibernate entity bidirectional relationships with Jackson JsonIgnoreProperties, CRUD RESTful APIs, Spring Data REST, MySQL and Docker.

In practice, you may also like to handle the JPA/Hibernate circular references/dependencies problem with DTO design pattern. Check out the following tutorial as one of the approaches
MapStruct Example of Mapping JPA/Hibernate Entity with DTO

What you'll need

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

Project structure

Project dependencies

Define JPA Entities Bidirectional Relationships with Jackson circular references handling

Jackson @JsonIgnoreProperties will prevent specified fields from being serialized or deserialized.

Lombok @EqualsAndHashCode with exclude will ignore specified fields on the generated equals and hashCode function of Lombok @Data

Define Repository

Spring Data REST will auto create RESTful APIs based on your domain model and repository.

Application Configurations

Run with JDK/OpenJDK and Maven

Type the below command at the project root directory

mvn clean spring-boot:run  

Test circular references handling and RESTful APIs with curl

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

Find all books

curl http://localhost:8080/books

Find authors of book id 1

curl http://localhost:8080/books/1/authors

Find books of author id 1

curl http://localhost:8080/authors/1/books

Source code