ooozguuur
ooozguuur

Reputation: 3476

JsonManagedReference vs JsonBackReference

I would like to know the difference between @JsonManagedReference and @JsonBackReference in Jackson?

Upvotes: 70

Views: 103208

Answers (5)

David
David

Reputation: 20073

@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 depend on the direction of your relationship:

public class User {
    public int id;
    public String name;
 
    @JsonManagedReference
    public List<Item> userItems; 
} 

public class Item {
    public int id;
    public String itemName;
 
    @JsonBackReference
    public User owner; 
 }

A useful guide for more details: https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

Upvotes: 83

HopeKing
HopeKing

Reputation: 3503

@JsonManagedReference -> Manages the forward part of the reference and the fields marked by this annotation are the ones that get serialized

@JsonBackReference -> Manages the reverse part of the reference and the fields/collections marked with this annotation are not serialized.

Use case: You have one-to-many or many-to-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 error occurs because Jackson (or some other similar) tries to serialize both ends of the relationship and ends up in a recursion.

@JsonIgnore performs similar functions but the annotations mentioned above are preferable.

Upvotes: 14

Shamsul Arefin
Shamsul Arefin

Reputation: 1917

The solution that worked for me is creating a seperate DTO class. where I dont have any field that has @jsonbackreference annotation and also No field which is a Model (which can contain inside a jsonbackreference or jsonmanagedreference).

I think the solution stems from incorrect mapping or inifite recursion of fields.

Upvotes: 0

Andrew S.
Andrew S.

Reputation: 942

As write Rajat Verma, his solution works perfectly. Thanks man you saved me lot of time and anger :-)

The important Part:
You need define fields as List, I had that as Set before and this solution NOT WORKING (appears as infinite loop)!

I add my solution:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class)
public class Agent {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(mappedBy = "subscribers")
    @ApiModelProperty(dataType = "List", example = "[1,2,3]") // for Swagger
    @JsonIdentityReference(alwaysAsId = true) // show only id of Topic
    private final List<Topic> subscribeTopics = new ArrayList<>()
}

 @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class)
 public class Topic {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToMany(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name = "topic_agent",
        joinColumns = @JoinColumn(name = "fk_topic_id"),
        inverseJoinColumns = @JoinColumn(name = "fk_agent_id"))
    @ApiModelProperty(dataType = "List", example = "[1,2,3]")
    @JsonIdentityReference(alwaysAsId = true)
    private final List<Agent> subscribers = new ArrayList<>();
 }

Upvotes: 7

ooozguuur
ooozguuur

Reputation: 3476

@JsonManagedReference and @JsonBackReference are designed to handle this two-way linkage between fields, one for Parent role, the other for Child role.

For avoiding the problem, linkage is handled such that the property annotated with @JsonManagedReference annotation is handled normally (serialized normally, no special handling for deserialization) and the property annotated with @JsonBackReference annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

Upvotes: 5

Related Questions