我试图在同一个类中映射父级和子级关系:
public class Category {
@Id
@SequenceGenerator(name = "categorySeq", sequenceName = "category_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "categorySeq")
@Column(name = "category_id", nullable = false)
private Long id;
@Column(name = "code", nullable = true)
private String code;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "parent_id", nullable = true)
private Long parentId;
@ManyToOne
@JoinColumn(name = "parent_id", insertable = false, updatable = false)
public Category parentCategory;
@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL)
public List<Category> subCategories = new ArrayList<Category>();
}
当我对类别进行GET时,我只获得parentCategory和子类别,结果为null。我希望父条目和子条目都在GET上返回。有什么问题吗?
那么在关系的反面,我必须通过设置FetchType急切地获取它。EAGER,它检索子条目,但现在Jackson抱怨无限循环,我不得不使用@JsonIgnore。但是,如果我使用@JsonIgore,它违背了这个问题的目的,因为我需要看到子条目。
但我想我意识到,要解析整个层次结构树,我可以递归地遍历每个子节点的父节点。
@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Category> subCategories = new ArrayList<Category>();