问题描述
我不太了解 @XmlIDREF
和 @XmlID
的工作方式.通过使用 XmlIDREF
,我仅创建对实际元素的引用.但是, 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
.
我想创建对类 Publication
的引用.用 @XmlIDREF
注释发布列表是否足够?
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;
}
推荐答案
不,那只是您需要的一半.
No, that's only one half of what you need.
-
您已经拥有此功能:使用
@XmlIDREF
标记关系的引用端(从Author
指向Publication
).
You already have this:With
@XmlIDREF
you mark the referencing side of the relation(pointing fromAuthor
toPublication
).
public class Author {
...
@XmlIDREF
@XmlElement(name = "publication")
public List<Publication> getPublications() {
return publications;
}
...
}
您还需要标记所引用的一侧( Publication
本身)通过使用 @XmlID
注释其属性之一,例如:
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;
}
...
}
然后您就可以像下面的示例一样处理XML内容:
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>
您会看到XML引用(例如< publication> p-101</publication>
)映射到Java对象引用(在 List< Publication>出版物
中).
You see, the XML references (like <publication>p-101</publication>
)are mapped to Java object references (in List<Publication> publications
).
这篇关于如何使用@XmlIDREF和@XmlID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!