Skip child to fetching of parent - JPA

Viewed 3320

I am facing an issue where the data is getting fechted recursively. I wanted to avoid the child to fetch the parent data. Which is causing a recursive issue. I have mentioned the code below

Pojo Structure

class Parent  {
    ..
    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    private List<Child> childs;

    ..
    }

class Child {
    ..
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentId")
    private Parent parent;
    ..
    }

Fetching the data like this

 `  em = EMF.get().createEntityManager();
    Query q = em.createQuery("Select p from Parent p", Parent.class);
    List<Parent> parents = q.getResultList();
    // Till this point all looks good but when the code gets executed 
    parent.getChilds();
`

It is fetching the data like this:

Parent
child1
    Parent
        child2
            Parent
                child2
                    Parent
                ..
        ..
child2
..

Which I dont need I just want the data like this:

Parent1
    child1
    child2
Parent2
    child1
    child2
    child3
4 Answers

It'll work as infinite loop for hefty data. Best practice is to mention @JsonIgnore at child class column. Thank me Later

To avoid this problem of cyclic references, I used a Mapper with MapStruct (see official documentation for a quick setup) :

Then I can easily write a mapper to ignore a property like this :

public interface SecondaryObjectMapper {
  @Mapping(target = "primaryObject.secondaries", ignore=true),
  SecondaryObjectDto toSecondaryObjectDto(SecondaryObject source);
}

and use it like this for example :

repository.findAll(pageable).map(secondaryObjectMapper::toSecondaryObjectDto)

To Avoid this issue , Please declare below annotation Parent & Child getter methods

   @JsonBackReference
    public Parent getParent() {
        return parent;
    }

@JsonManagedReference
    public List<Child> getChilds() {
    return childs;
    }
Related