问题描述
我有一个包含循环的对象图.如何让 JAXB 处理这个问题?我尝试在子类中使用 @XmlTransient 注释,但 JAXB 编组器仍然检测到循环.
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/关系
@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 实现,您需要在模型类(即合同)中包含一个 jaxb.properties 文件,其中包含以下条目:
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