hibernateinfinite-loopbidirectional-relation

How to break infinite parent - children loop in Hibernate


I have an app with Pages, and each of them might have child Pages:

Page.java

public class Page{
  ...
  @Nullable
  @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  private Page parentPage;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "parentPage")
  private List<Page> childPages;
  ...
}

I want to display a link << Back to parent page on each page, and to have links to all its children:

view-page.html

<div ng-if="currentPage.parentPage">
  <a href="#/view-page?pageId={{currentPage.parentPage.id}}">Back to {{currentPage.parentPage.title}}</a>
</div>
...
<div ng-repeat="row in currentPage.childPages">
  <a href="#!/view-page?pageId={{row.id}}">{{row.title}}</a>
</div>

This causes an infinite loop parent - child - parent - ...

I tried with @JsonIgnore, but then I lose the info I need (whether it's a parent or a child). I also tried to annotate the parent with @JsonManagedReference and the list of child pages with @JsonBackReference. Then I could see the parent, but not the children. My next step will be to try and write a custom serializer.

So my question is - does anyone have an idea how can I get a parentPage property and still being able to see children without getting into an infinite loop child - parent - child - parent...?


Solution

  • I've found a solution. In one of the relations I could use @JsonIgnore. In other case I needed to use a custom serializer where I will not load children.