JsonManagedReference vs JsonBackReference

  • @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.


@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; 
 }

I prefer
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class)
where property is the name of primary key field and scope is Type of it

Tags:

Java

Jackson