#AskMe

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:

Example: User to display its user roles

User.java

@Entity
public class User implements java.io.Serializable {
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private long id;
 
 @Column(name="name")
 private String name;

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

...

Roles.java

@Entity
public class Role implements java.io.Serializable {

 @Id 
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int id;

 @ManyToMany(mappedBy="roles")
 @JsonBackReference
 private Set<User> users = new HashSet<User>();

...

Relationship: ManyToMany

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

User.java

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

Item.java

@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: