JPA无法检索父子映射的子条目

时间:2015-10-02 07:58:45

标签: jpa orm mapping parent-child

我正在尝试使用同一个类映射父子关系:

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>();

}

当我对类别i进行GET时,只获取parentCategory,子类别为nu​​ll。我希望在GET上返回父条目和子条目。任何想法在这里有什么问题?

1 个答案:

答案 0 :(得分:0)

好吧,在关系的反面,我必须通过设置FetchType.EAGER来急切地获取它,它会检索子条目,但现在Jackson抱怨无限循环,我必须使用@JsonIgnore。但是,如果我使用@JsonIgore,它就会失败这个问题的目的,因为我需要查看子条目。

但是我想我已经意识到要解析整个层次结构树,我可以通过递归遍历每个子节点的父节点来实现。

@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Category> subCategories = new ArrayList<Category>();