This problem is discussed in detail in the link http://forums.java.net/jive/thread.jspa?threadID=13670
Scenario:
State state=new State();
state.setName("Georgia");
Country ctry=new Country();
ctry.setName("USA");
state.setCountry(ctry);
ctry.setState(state);
//Invoke the web service here
The Error which occurs is: A cycle is detected in the object graph. This will cause infinitely deep XML
This is because of the cyclic dependency of reference between State and Country.
Solution:
Do not set the parent as a reference in child [Here parent is Country and State is child]
State state=new State();
state.setName("Georgia");
Country ctry=new Country();
ctry.setName("USA");
ctry.setState(state);
//Invoke the web service here
Place the following annotations in State and Country.
@XmlRootElement
public class Country {
private String name;
private State state;
//Getters and setters for name and state
}//end of class Country
The State is as below [Note the afterUnmarshal method. It is used to set the reference to parent which otherwise would have been set in the web service client before marshalling (but causes error)].
The idea is to set the parent reference on the server side after unmarshal to avoid the error.
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
public class State {
@XmlAttribute
String name;
@XmlTransient
private Country country;
public void afterUnmarshal(Unmarshaller u, Object parent) {
this.setCountry((Country) parent);
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
For more information, please refer
https://jaxb.dev.java.net/guide/Mapping_cyclic_references_to_XML.html