You can use @XmlID
in combination with @XmlIDREF
Employee
On the Employee
class you need to annotate which field/property is going to be the "key" for the object. In JAXB this is done with the @XmlID
annotation.
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
@XmlAttribute
@XmlID
private String id;
}
Company
In the Company
class we will indicate that we want to marshal instances of Employee
as a reference to the real object. This is done using the @XmlIDREF
annotation.
@XmlAccesorType(XmlAccessType.FIELD)
public class Company {
@XmlElementWrapper
@XmlElement(name="elementref")
@XmlIDREF
private List<Employee> employees;
}
Root
In order for @XmlIDREF
to work the object must mapped somewhere else with an @XmlElement
annotation. In this example this happes in the Root
class.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
private Company company;
@XmlElement(name="employee")
private List<Employee> employees;
}
For More Information
You can read more about @XmlID
and @XmlIDREF
on my blog: