JAXB Mapping cyclic references to XML(JAXB 将循环引用映射到 XML)
问题描述
我有一个包含循环的对象图.如何让 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
这篇关于JAXB 将循环引用映射到 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JAXB 将循环引用映射到 XML
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01