Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JPA无法检索父子映射的子项_Jpa_Orm_Mapping_Parent Child - Fatal编程技术网

JPA无法检索父子映射的子项

JPA无法检索父子映射的子项,jpa,orm,mapping,parent-child,Jpa,Orm,Mapping,Parent Child,我正在尝试映射同一类中的父级和子级关系: public class Category { @Id @SequenceGenerator(name = "categorySeq", sequenceName = "category_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "categorySeq") @

我正在尝试映射同一类中的父级和子级关系:

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

}
公共类类别{
@身份证
@SequenceGenerator(name=“categorySeq”,sequenceName=“category\u id\u seq”,allocationSize=1)
@GeneratedValue(策略=GenerationType.SEQUENCE,generator=“categorySeq”)
@列(name=“category\u id”,null=false)
私人长id;
@列(name=“code”,nullable=true)
私有字符串码;
@列(name=“name”,nullable=false)
私有字符串名称;
@列(name=“parent\u id”,nullable=true)
私人长父ID;
@许多酮
@JoinColumn(name=“parent\u id”,insertable=false,updateable=false)
公共类;
@OneToMany(mappedBy=“parentCategory”,cascade=CascadeType.ALL)
公共列表子类别=新建ArrayList();
}

当我做一个GET-on类别时,我只得到parentCategory,子类别显示为null。我希望在GET上同时返回父项和子项。你知道这里出了什么问题吗?

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

但我想我意识到,要解析整个层次结构树,我可以通过递归遍历每个子级的父级来完成

@OneToMany(mappedBy = "parentCategory", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<Category> subCategories = new ArrayList<Category>();
@OneToMany(mappedBy=“parentCategory”,cascade=CascadeType.ALL,fetch=FetchType.EAGER)
公共列表子类别=新建ArrayList();

嗯?您定义了一个序列生成器,然后定义使用标识策略(而不是序列)。毫无意义。完全标识是使用“自动增量”而不是序列哦,是的,它应该是序列。谢谢。为什么您要将父id映射为基本映射和关系?由于您已将关系有效地标记为只读,因此在添加父级时,是否也将子级添加到父级的子类别列表中?我建议您切换它,使parentId为只读,并从关系中设置parent_id,以便JPA可以在检索父序列值时为您设置字段,并验证您正在设置此双向关系的两侧。感谢您指出这一点。