prev table of contents next

6.2.11 Annotations for Object References: XmlID, XmlIDREF

The section Referring to Another XML Element describes the usefulness of using references rather than repeatedly serialized content. Two annotations instruct JAXB to use references: XmlID must define a field of some class with type java.lang.String that is suited to be used as a key, and XmlIDREF is attached to any field that references objects of that class. Both annotations may be used in addition to XmlElement.

We'll illustrate an application of these annotations in a somewhat more sophisticated pattern resulting from the possibility of attaching XmlIDREF to a field of some collection type. In this case, the collection item type must contain an id field.

Below is a group of Java classes defining an Item class and a Document class. The latter contains a list of existing items and a Cluster object that wraps a Set<Item> field containing references to some of the items from the list.

import javax.xml.bind.annotation.*;

public class Item {

    private String id;
    private String name;

    public Item(){}

    @XmlID
    public String getId(){ ... }
    public void setId( String value ){ ... }

    @XmlElement
    public String getName(){ ... }
    public void setName( String value ){ ... }
}

import java.util.HashSet;
import java.util.Set;

import javax.xml.bind.annotation.*;

public class Cluster {

    private Set<Item> items;
    private String title;

    public Cluster(){ ... }

    @XmlIDREF
    public Set<Item> getItems(){ ... }
}

package elset;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Document {

    private Cluster    cluster;
    private String     title;
    private List<Item> items;

    public Document(){ ... }

    @XmlElement
    public Cluster getCluster(){ ... }
    public void setCluster( Cluster value ){ ... }

    @XmlElement
    public String getTitle(){ ... }
    public void setTitle( String value ){ ... }

    @XmlElement
    public List<Item> getItems(){ ... }
}


prev table of contents next