有一个结构。我想以这种方式链接这三个实体:公司应包含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]




如何避免这种循环?

最佳答案

您的模型中存在双向关系。要解决此问题,您可以执行以下操作:

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

1-@XmlTransient

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

2-@XmlID / @XmlIDREF

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


http://blog.bdoughan.com/2010/10/jaxb-and-shared-references-xmlid-and.html


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

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

您可以在此用例中使用MOXy的@XmlInverseReference扩展名。在编组操作中,它的作用类似于@XmlTransient,但仍将在取消编组中填充值。


http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html
http://blog.bdoughan.com/2013/03/moxys-xmlinversereference-is-now-truly.html

关于java - JAXB。建议正确的注释,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19897925/

10-14 05:45