Infinite Recursion with Jackson JSON, Spring MVC 4.2 and Hibernate JPA issue

It can be done by many ways

  • Remove the getter method from one of the class.
  • Use @JsonIgnore in One of the class (Problem : In Both above cases it will ignore the field from the result.)

    If You use below annotations, It will include the field also

  • @JsonManagedReference, @JsonBackReference
  • @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

Just put @JsonIgnore

@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "userClass")
public List<User> getUsers() {
     return this.users;
}

This will ignore lazy load object and fix your issue.

Update

  • According to Udara Seneviratne answer, You can handle bi-directional relationship by @JsonManagedReference, @JsonBackReference.

@JsonIgnore just ignore the annotated field from the result. If you need to include exception caused field also with the result, use @JsonManagedReference, @JsonBackReference according to following tutorial. http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

If a class has more than one bi-directional relationships, better to use @JsonIdentityInfo