Jenew
Jenew

Reputation: 39

How to use @XmlIDREF and @XmlID

I don't quite understand how @XmlIDREF and @XmlID work together. By using XmlIDREF I only create a reference to the actual element. However what is the use case for XmlID.

I want to create a reference to the class Publication. Is it enough to annotate the publication List with @XmlIDREF?

public class Author {

    private String id;
    private String name;
    private List<Publication> publications = new LinkedList<>();

    public Author() {
        super();
    }
    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    @XmlIDREF
    public List<Publication> getPublications() {
        return publications;
    }

Upvotes: 0

Views: 1986

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

I want to create a reference to the class Publication. Is it enough to annotate the publication List with @XmlIDREF?

No, that's only one half of what you need.

  • You already have this: With @XmlIDREF you mark the referencing side of the relation (pointing from Author to Publication).

    public class Author {
    
        ...
    
        @XmlIDREF
        @XmlElement(name = "publication")
        public List<Publication> getPublications() {
            return publications;
        }
    
        ...
    
    }
    
  • You also need to mark the referenced side (the Publication itself) by annotating one of its properties with @XmlID, for example like this:

    public class Publication {
    
        ...
    
        @XmlID
        @XmlElement
        public String getId() {
            return id;
        }
    
        ...
    }
    

Then you are able to process XML content like this example:

<root>
    <publication>
       <id>p-101</id>
       <title>Death on the Nile</title>
    </publication> 
    <publication>
       <id>p-102</id>
       <title>The murder of Roger Ackroyd</title>
    </publication> 
    ...
    <author>
       <id>a-42</id>
       <name>Agatha Christie</name>
       <publication>p-101</publication>
       <publication>p-102</publication>
    </author>
    ...
</root>

You see, the XML references (like <publication>p-101</publication>) are mapped to Java object references (in List<Publication> publications).

Upvotes: 1

Related Questions