JPA:选择具有oneToMany关联的父母和子女

时间:2017-09-04 09:25:39

标签: hibernate jpa hibernate-mapping hibernate-onetomany

实施一对多关系并选择父和子 我有onetomany关系,我想进行查询(选择*)

Folders.java

@Entity
@Table(name = "FOLDERS")
public class Folders implements Serializable {
    @Id
    @Column(name = "id")
    Long id;
    @ManyToOne
    @JoinColumn(name = "Folder_Author", insertable=false, updatable=false)
    private Authors author;
    // Getter + setter
}

Authors.java

@Entity
@Table(name = "AUTHORS")
public class Authors implements Serializable {

    @Id
    @Column(name = "id")
    Long id;
    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    @JoinColumn(name = "Folder_Author", referencedColumnName = "id", nullable=false)
    private List<Folders> folders = new ArrayList<Folders>();
}

我的要求:

Query query = em.createQuery("SELECT f FROM Folders f");
return query.getResultList();

我得到了这个结果:

[
    {   
        "id":29,
        "noFolder":"0017",
        "author":{
            "id":9,
            "name":"Alpha",
            "service":null,
            "folders":[
                {"id":29,
                "noFolder":"0017",
                "author":{
                    "id":9,
                    "name":"Alpha",
                    "service":null,
                    "folders":[
                    {
                        "id":29,
                        "noFolder":"0017",
                        "author":{
                        "id":9,
                        "name":"Alpha",
                        "service":null,
                        "folders":[
                            ..
                            ..
            }
]       

我的代码有什么问题?当我执行查询时有什么问题我得到了这个结果.. ..我想得到这个结果

[
    {   
        "id":29,
        "noFolder":"0017",
        "author":{
            "id":9,
            "name":"Alpha",
            "service":null,
            }
    }
]           

2 个答案:

答案 0 :(得分:3)

只需在您的收藏字段中使用@JsonIgnore,如下所示:

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
    @JoinColumn(name = "Folder_Author", referencedColumnName = "id", nullable=false)
    @JsonIgnore
    private List<Folders> folders = new ArrayList<Folders>();

答案 1 :(得分:2)

在作者类的文件夹列表中使用@JsonBackReference以防止递归序列化。

另见here