Wednesday, October 18, 2017

JPA bidirection mapping JSON infinite loop issue

Employee and EmployeeTitle are parent and child class.

I made an extreme example here. Both fetch is eager. Actually JPA can deal it, which does not create infinite loop. The trouble is when converting the JAVA object to JSON when you need pass the object through the restful service. It reports infinite loop.
This article describes different ways to deal with JSON infinite loop. Most of them is to ignore one on either parent or child object to break the infinite loop.

In my case I don't want to ignore any part.
The solution is to use @JsonIdentityInfo to resolve cyclic dependencies in an object graph by using an ID/reference mechanism so that an object instance is only completely serialized once and referenced by its ID elsewhere.

Employee is easy. Only need add @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "empNo")
 This is a legacy database which is using composite primary key. But JsonIdentityInfo seems not support composite key. So I have to serialize the composite key to String. You can make it JSON string, that also works.
Now if we get Employee object, the JSON is like this

if we get employeeTitle object, the JSON is like this

Nothing was ignore on either side.

No comments:

Post a Comment