JAXB映射对XML的循环引用 [英] JAXB Mapping cyclic references to XML
问题描述
我有一个包含循环的对象图。如何让JAXB处理这个问题?我尝试在子类中使用 @XmlTransient
注释,但JAXB marshaller仍然检测到循环。
I have an object graph that contains a cycle. How do I get JAXB to handle this? I tried using the @XmlTransient
annotation in the child class but the JAXB marshaller still detects the cycle.
@Entity
@XmlRootElement
public class Contact {
@Id
private Long contactId;
@OneToMany(mappedBy = "contact")
private List<ContactAddress> addresses;
...
}
@Entity
@XmlRootElement
public class ContactAddress {
@Id
private Long contactAddressId;
@ManyToOne
@JoinColumn(name = "contact_id")
private Contact contact;
private String address;
...
}
推荐答案
使用JAXB的好处在于它是一个具有多个实现的标准运行时(就像JPA一样)。
The good thing about using JAXB is that it is a standard runtime with multiple implementations (just like JPA).
如果使用EclipseLink JAXB(MOXy)然后您可以使用许多扩展来处理JPA实体,包括双向关系。这是使用MOXy @XmlInverseReference批注完成的。它与marshal上的@XmlTransient类似,并在unmarshal上填充目标到源的关系。
If you use EclipseLink JAXB (MOXy) then you have many extensions available to you for handling JPA entities including bi-directional relationships. This is done using the MOXy @XmlInverseReference annotation. It acts similar to @XmlTransient on the marshal and populates the target-to-source relationship on the unmarshal.
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA/Relationships
@Entity
@XmlRootElement
public class Contact {
@Id
private Long contactId;
@OneToMany(mappedBy = "contact")
private List<ContactAddress> addresses;
...
}
@Entity
@XmlRootElement
public class ContactAddress {
@Id
private Long contactAddressId;
@ManyToOne
@JoinColumn(name = "contact_id")
@XmlInverseReference(mappedBy="addresses")
private Contact contact;
private String address;
...
}
其他扩展可用,包括支持复合键和嵌入式密钥类。
Other extensions are available including support for composite keys & embedded key classes.
要指定EcliseLink MOXy JAXB实现,您需要在模型类(即Contract)中包含一个jaxb.properties文件,其中包含以下条目: / p>
To specify the EcliseLink MOXy JAXB implementation you need to include a jaxb.properties file in with your model classes (i.e. Contract) with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
这篇关于JAXB映射对XML的循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!