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
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01