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