Correctness1 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
Bug pattern name: Infinite Recursion with Jackson Library
User-Item (1:N)
public class User {
public int id;
public String name;
public List<Item> userItems;
}
------------------------------------------------
public class Item {
public int id;
public String itemName;
public User owner;
}
------------------------------------------------
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenSerializing_thenException()
throws JsonProcessingException {
User user = new User(1, "John");
Item item = new Item(2, "book", user);
user.addItem(item);
new ObjectMapper().writeValueAsString(item);
}
- Use @JsonManagedReference, @JsonBackReference
- Use @JsonIdentityInfo
- Use @JsonIgnore
- Use @JsonView
- Use a Custom Serializer
- Deserialize With @JsonIdentityInfo
- Use Custom Deserializer
1 Two entities have a reference to each other and the relation of them is one to many. 2 The many side is serialized.
For Jackson to work well, one of the two sides of the relationship should not be serialized, in order to avoid the infite loop that causes your stackoverflow error.
https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion