Developing JAXB Applications Using EclipseLink MOXy, Release 2.6
  Go To Table Of Contents

Mapping Bidirectional Relationships

In order to map bidirectional relationships in EclipseLink MOXy, the back-pointer must be annotated as an @XmlInverseReference. Without this annotation, the cyclic relationship will result in an infinite loop during marshalling.

@XmlInverseReferences must specify the mappedBy attribute, which indicates the property on the opposite side of the relationship.

In Example 7-11, an Employee has a collection of PhoneNumbers, and each PhoneNumber has a back-pointer back to its Employee:

Example 7-10 Using the @XMlInverseReference Annotation

public class Employee {
   private String name;
   private List<PhoneNumber> phones = new ArrayList<PhoneNumber>();
public class PhoneNumber {
   private String number;
   private Employee employee;

Example 7-11 shows how to define this mapping in EclipseLink's OXM metadata format:

Example 7-11 Sample XML Mapping

<java-type name="Employee">
      <xml-element java-attribute="name" type="java.lang.String"/>
      <xml-element java-attribute="phones" type="PhoneNumber" container-type="java.util.ArrayList"/>
<java-type name="PhoneNumber">
      <xml-element java-attribute="number" type="java.lang.String"/>
      <xml-inverse-reference java-attribute="employee" type="Employee" mapped-by="phones" />
In addition, when using @XmlInverseReference, it is not necessary to explicitly set the back-pointer in your Java code; EclipseLink will do this for you automatically:
Employee emp = new Employee();
emp.setName("Bob Smith");
PhoneNumber p = new PhoneNumber();
// Not Necessary
// p.setEmployee(emp);

@XmlInverseReference back-pointers can be used with the following types of mappings:

@XmlInverseReference can be particularly useful when mapping JPA entities to XML (see "Using XML Bindings")

See also

For more information, see: