This is a simple reproduction of a sample Spring Boot/JPA application to show that
@JsonIgnoredoes not work withjava.util.Set, but does withjava.util.List, when using the current latest version of Jackson and Spring Boot.This project implements the
@ManyToManyexample on https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/.
This reproduction is for the following issue: FasterXML/jackson-databind#2782.
- When using a
@ManyToManyor@OneToManyannotation on aList, when using Jackson to serialize the owning entity, Jackson will recursively serialize the back-referenced entity and throw an exception. - To fix this, you can add
@JsonIgnoreon the back part of the reference, as described in https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion#json-ignore - This works when the back-reference is a
List, but not aSet. - You may want to use a
Setto optimize Hibernate queries, as explained in this vladmihalcea article.
- Maven 3.6.3 (bundled as wrapper)
- Java 13.0.2
- Spring Boot Starter Data JPA 2.3.1
- Spring Boot Starter Web 2.3.1
- H2 Database 1.4.200
- Lombok 1.18.12
- Jackson dependencies (transitive) 2.11.0
- IntelliJ 2020.1.2 Ultimate (if it matters)
You must have Java 13 installed.
If using IntelliJ, you must have the Lombok Plugin installed.
- In File > Settings > Other Settings > Lombok Plugin, ensure that Enable Lombok plugin is checked.
- In File > Settings > Build, Execution, Deployment > Compiler > Annotation Processors, ensure that Enable annotation processing is checked.
- Import the root
pom.xmlas a Maven project and use default options. - Right-click
DemoApplicationinsrc/main/java/com/example/demoand clickRun DemoApplication. - The application will build and run on http://localhost:8080.
# Navigate to demo directory
cd C:\<path-to-demo-directory>\jackson-demo
# Build project
mvnw clean install -DskipTests
# Run application
java -jar target\demo-0.0.1-SNAPSHOT.jar-
Make a GET request to http://localhost:8080/api/posts-with-list.
-
This should return:
[ { "id": 1, "title": "Post 1", "tagsWithList": [ { "id": 1, "name": "foo" }, { "id": 2, "name": "bar" } ] } ]
-
Make a GET request to http://localhost:8080/api/posts-with-set.
-
It should return an HTTP 500 error page with the following error logged to the console:
Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.example.demo.models.PostWithSet["tagsWithSet"])]
- Right-click
PostControllerTestinsrc/test/java/com/example/demo/controllersand click Run 'PostControllerTest'.
mvnw test