Solving the recursive Json data generation in Java Spring

Let me presume a quick remark or note on the use of jsonManagedReference, jsonBackReference or JsonIdentityInfo annotation when you will manage to display json data from the entity while working on Spring 3 and Jackson.

The work likely in case you need to exchange the data via Json such as developing application with AngularJS and Spring, you might face most of the issue the recursive Json data generated from child entity to parent entity vice versa.

To solve the issue, jsonManagedReference, jsonBackReference or JsonIdentityInfo help.

Relationship: OneToMany or ManyToOne

Use jsonManagedReference, jsonBackReference while:

  • Place @jsonManagedReference annotation to parent entity in order to display the list of child entity.
  • Place @jsonBackReference annotation to child entity on the attribute of User in order to prevent the loop display of parent entity.

Example: User to display its user roles

public class User implements {
 private long id;
 private String name;

 @JoinTable(name="users_roles",joinColumns=@JoinColumn(name = "user_fk"),
 inverseJoinColumns=@JoinColumn(name = "role_fk"))
 private Set<Role> roles = new HashSet<Role>();


public class Role implements {

 private int id;

 private Set<User> users = new HashSet<User>();


Relationship: ManyToMany

  • Use @JsonIdentityInfo on both parent and child entity
  • We call this relationship as Bidirectional relationship

Example: User buys some items and the item needs to know who bought it

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class User { ... }

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Item { ... }

Related Posts

Following posts are really helpful around all the explain of above short remark for you to discover more:

One reply on “Solving the recursive Json data generation in Java Spring”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.