5

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 ?

facundofarias
  • 2,973
  • 28
  • 27
m_vitaly
  • 11,856
  • 5
  • 47
  • 63
  • 1
    If XStream does the job, why go hunting for something else? This question is too open-ended. – skaffman Jan 23 '12 at 09:55
  • @skaffman I would prefer if there was a JAX-B implementation with this feature – m_vitaly Jan 23 '12 at 12:18
  • possible duplicate of [JAXB Mapping cyclic references to XML](http://stackoverflow.com/questions/3073364/jaxb-mapping-cyclic-references-to-xml) – m_vitaly Jan 25 '12 at 13:06
  • Seems it was almost exact duplicate of http://stackoverflow.com/questions/3073364/jaxb-mapping-cyclic-references-to-xml – m_vitaly Jan 25 '12 at 13:06

2 Answers2

2

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

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Well, that result does not capture the cyclic nature of the graph? Where's the ID on `` and reference to that on ´`? – mgaert Jan 23 '12 at 11:07
  • The ID is not required. `A` references `B` through a containment relationship. Then we used @XmlInverseReference to indicate that when when `refToB` is being populated, that `refToA` should be populated as well. This strategy is also used by JPA implementations. If you want to use ids, check out JAXB's `@XmlID`/`@XmlIDREF`: http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html – bdoughan Jan 23 '12 at 11:59
1

A couple of years ago I worked with Betwixt. They claim support, see http://commons.apache.org/betwixt/faq.html#cycles

Alas, setting up a simple test did not work for me so far, output merely is <A id="1"><B/></A>, with the pointer to A in B silently ignored. There must be some mapping option that I failed to set...

mgaert
  • 2,338
  • 21
  • 27