2

有一个结构。我想以这种方式链接三个实体:公司应该包含 id、公司名称和部门列表,每个部门都有一个工人列表、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]

如何避免这个循环?

4

1 回答 1

0

您的模型中有双向关系。要解决它,您可以执行以下操作:

使用标准 JAXB 元数据的解决方案

1 -@XmlTransient

您可以用 映射关系的一个方向@XmlTransient。这将导致字段/属性无法编组以防止无限循环。此字段/属性也不会解组,这意味着您需要自己填充它。

2 - @XmlID/@XmlIDREF

@XmlIDREF是您映射共享引用的方式,JAXB 您可以使用它来映射反向指针关系。

利用 EclipseLink JAXB (MOXy) 扩展的解决方案

注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。

对于这个用例,您可以使用 MOXy 的@XmlInverseReference扩展。它的作用类似于@XmlTransientmarshal 操作,但仍会填充 unmarshal 上的值。

于 2013-11-11T14:31:19.317 回答