Search code examples
javaxmljaxbmarshallingidref

Which Java XML binding framework supports circular/cyclic dependencies?


I've got two classes:

public class A {
  B refToB;
}

public class B {
  A refToA;
}

they don't have unique id fields (which are required for JAX-B XMLID and XMLIDREF).

Object instances:

A a = new A();
B b = new B();
a.refToB = b;
b.refToA = a;

I want to marshall a to XML while storing the circular/cyclic dependency, something like:

<a id="gen-id-0">
  <b>
    <a ref-id="gen-id-0" />
  </b>
</a>

One of the frameworks I've found that supports this is XStream: http://x-stream.github.io/graphs.html

What other frameworks support this feature ?

Does some JAX-B implementations support it ?


Solution

  • Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

    MOXy has the @XmlInverseReference extension for mapping bidirectional relationships.

    A

    import javax.xml.bind.annotation;
    
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    public class A {
      @XmlElement(name="b")
      B refToB;
    }
    

    B

    import javax.xml.bind.annotation;
    import org.eclipse.persistence.oxm.annotations.XmlInverseReference;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class B {
      @XmlInverseReference(mappedBy="refToB")
      A refToA;
    }
    

    XML

    The above classed will map to the following XML

    <a>
        <b/>
    <a>
    

    For More Information