有一个结构。我想以这种方式链接这三个实体:公司应包含 id、公司名称和部门列表,每个部门都有 worker 列表、id 和部门名称。每个worker都有名字,id。
+Company
-int companyId
-String companyName
-Set<Department> listOfDepartments = new HashSet<Department>();
+Department
-int departmentId
-String departmentName
-Set<Worker> listOfWorkers = new HashSet<Worker>();
+Worker
-int workerId
-String workerName
@XmlRootElement(name="Company")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
public class Company {
@XmlAttribute(name = "id")
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int companyId;
@XmlElement(name = "companyName")
private String companyName;
@XmlElement(name="Department")
@OneToMany(mappedBy = "company", cascade=CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Department> listOfDepartments = new HashSet<Department>();
@XmlRootElement(name="Department")
@XmlAccessorType(XmlAccessType.FIELD)
@Entity
public class Department {
@XmlAttribute(name = "id")
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idDepartment;
@XmlElement(name = "departmentName")
private String departmentName;
@ManyToOne()
@JoinColumn(name="companyId")
private Company company;
@XmlElement(name="Worker")
@OneToMany(mappedBy = "department", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Worker> listOfWorkers = new HashSet<Worker>();
@XmlRootElement(name="Worker")
@Entity
public class Worker {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int idWorker;
private String workerName;
@ManyToOne
@JoinColumn(name="departmentId")
private Department department;
错误:
A cycle is detected in the object graph. This will cause infinitely deep XML: ru.eldarkaa.dto.Company@d1e43ed ->
ru.eldarkaa.dto.Department@6e55f58 -> ru.eldarkaa.dto.Company@d1e43ed]
如何避免这个循环?
最佳答案
您的模型中存在双向关系。要解决它,您可以执行以下操作:
使用标准 JAXB 元数据的解决方案
1 - @XmlTransient
您可以使用 @XmlTransient
映射关系的一个方向。这将导致字段/属性不编码以防止无限循环。此字段/属性也不会解码,这意味着您需要自己填充它。
2 - @XmlID
/@XmlIDREF
@XmlIDREF
是您使用 JAXB
映射共享引用的方式,您可以使用它来映射反向指针关系。
利用 EclipseLink JAXB (MOXy) 扩展的解决方案
注意:我是 EclipseLink JAXB (MOXy) JAXB (JSR-222) 的领导和成员专家组。
对于此用例,您可以使用 MOXy 的 @XmlInverseReference
扩展。它在编码操作中的作用类似于 @XmlTransient
,但仍会填充解码操作中的值。
关于java - JAXB。建议正确的注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19897925/