Web Services

     
 

Problem with circular relationship when using JAXWS and JAXB


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


 
 
 
 
 

« August 2008
SunMonTueWedThuFriSat
     
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
      
Today

Valid XHTML or CSS?

[This is a Roller site]
Theme by Rowell Sotto.
 
© Karthik