Java JAXB。建议正确的注释
有一个结构。我想以这种方式链接这三个实体:公司应该包含id、公司名称和部门列表,每个部门都有一个员工列表、id和部门名称。每个工人都有自己的名字、idJava JAXB。建议正确的注释,java,jaxb,annotations,Java,Jaxb,Annotations,有一个结构。我想以这种方式链接这三个实体:公司应该包含id、公司名称和部门列表,每个部门都有一个员工列表、id和部门名称。每个工人都有自己的名字、id +Company -int companyId -String companyName -Set<Department> listOfDepartments = new HashSet<Department>(); +Department -int departmentId -String departmentName
+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
如何避免这种循环?您的模型中存在双向关系。要解决此问题,您可以执行以下操作: 使用标准JAXB元数据的解决方案 1-
@xmltransive
您可以使用@xmltransive
映射关系的一个方向。这将导致字段/属性不封送,从而阻止无限循环。此字段/属性也不会解组,这意味着您需要自己填充它
2-@XmlID
/@XmlIDREF
@XmlIDREF
是如何将共享引用映射到JAXB
的,您可以使用它映射回指针关系
@XmlInverseReference
扩展。它的作用类似于封送处理操作中的@xmltransive
,但仍将填充解组操作中的值
@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]