This tutorial will walk you through the steps of creating an example on handling circular references/dependencies of JPA and 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 and 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+
Init project structure and dependencies
Project structure
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── hellokoding
│ │ ├── jpa
│ │ │ ├── book
│ │ │ │ ├── Author.java
│ │ │ │ ├── AuthorRepository.java
│ │ │ │ ├── Book.java
│ │ │ │ ├── BookPublisher.java
│ │ │ │ ├── BookPublisherRepository.java
│ │ │ │ ├── BookRepository.java
│ │ │ │ ├── Category.java
│ │ │ │ ├── CategoryRepository.java
│ │ │ │ ├── Publisher.java
│ │ │ │ └── PublisherRepository.java
│ │ │ └── JpaApplication.java
│ │ └── springboot
│ └── resources
│ └── application.properties
├── Dockerfile
├── docker-compose.yml
└── pom.xml
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 Repositories
Spring Data REST will auto create RESTful APIs based on your domain model and repository.
Config and Run
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