JsonManagedReference vs JsonBackReference
I would like to know the difference between @JsonManagedReference
and @JsonBackReference
in Jackson?
@JsonManagedReference is the forward part of reference – the one that gets serialized normally. @JsonBackReference is the back part of reference – it will be omitted from serialization.
So they really depend on the direction of your relationship
public class User {
public int id;
public String name;
@JsonBackReference
public List<Item> userItems;
}
public class Item {
public int id;
public String itemName;
@JsonManagedReference
public User owner;
}
- @JsonManagedReference -> Manages the forward part of the reference and the fields marked by this annotation are the ones that get Serialised
- @JsonBackReference -> Manages the reverse part of the reference and the fields/collections marked with this annotation are not serialised.
Use case: You have a one-many or many-many relationships in your entities/tables and not using the above would lead to errors like
Infinite Recursion and hence stackoverflow - > Could not write content: Infinite recursion (StackOverflowError)
The above errors occurs because Jackson (or someother similiar) tries to serialise both ends of the relationship and ends up in a recursion.
@JsonIgnore performs similiar functions but the above mentioned annotations are preferable.