JPA : Select parent and child with oneToMany relatinships

1.1k views Asked by At

Implemented one to many relationship and select parent and child I have a onetomany relationship and I want to do a query (select *)

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

My request :

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

I got this result :

[
    {   
        "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":[
                            ..
                            ..
            }
]       

What's wrong in my code ? What is the problem when I execute query I got this result .. .. I would like to get this result

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

There are 2 answers

2
Chaitanya On BEST ANSWER

Just use the @JsonIgnore on your collection field like this:

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

Use @JsonBackReference on the list of folders in the author class to prevent recursive serialization.

See also here