In a rest application, I use spring boot with jpa.
I have a class Lodger
who have
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger")
private List<Reference> referenceList;
In my class Reference, i have
@ManyToOne
@JoinColumn(name = "lodgerId")
private Lodger lodger;
when i call this method
@RequestMapping(value = "/lodgers/{lodgerId}", method = RequestMethod.GET)
public Lodger getLogderById(@PathVariable("lodgerId") long lodgerId) {
return lodgerService.getLodger(lodgerId);
}
I get this error
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]->org.hibernate.collection.internal.PersistentBag[0]->server.bean.Reference["lodger"]->server.bean.Lodger["referenceList"]...
Do not return entity with circular dependencies via REST webservice - create new DTO class, map entities fetched from database and return it in webservice.
More info here: http://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
Of course if you want you may use another mapping library, my personal favourite is Orika (http://orika-mapper.github.io/orika-docs/intro.html)
Solution:
Use
@JsonManagedReference
annotation for the first objects instantiated@JsonBackReference
annotation for the second objects instantiatedFirst:
Second:
If you primary keys in both tables are same name for example : id.
Add this
And to Reference class.
It happens when you have a cycle in return object and spring tries to serialize it to other type.
Try to create DTO or Value Object (simple POJO) without cycles from returned model and then return it.
Lets assume your code looks like below :-
Reference.class
When you notice at the toString() method written in both the POJO's, you will see that we are calling toString() of both the classes from either side which results in infinite no. of calls to toString() method from both sides which never terminates. To avoid this situation remove any the reference from toString() of Refernce.class[You may remove from Lodger class also.] So toString() of Reference class will not have lodger property in it.
So finally your Reference class will look like :-
Reference.class