0

我有一个带有页面的应用程序,每个应用程序都可能有子页面:

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;
  ...
}

我想<< Back to parent page在每个页面上显示一个链接,并链接到它的所有子页面:

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>

这会导致无限循环父-子-父-...

我尝试使用@JsonIgnore,但后来我丢失了我需要的信息(无论是父母还是孩子)。我还尝试用 . 注释父@JsonManagedReference页面和子页面列表@JsonBackReference。然后我可以看到父母,但看不到孩子。我的下一步将是尝试编写自定义序列化程序。

所以我的问题是 - 有没有人知道我怎样才能获得一个parentPage财产并且仍然能够看到孩子而不进入无限循环孩子 - 父母 - 孩子 - 父母......?

4

2 回答 2

0

我找到了解决方案。在我可以使用的关系之一中@JsonIgnore。在其他情况下,我需要使用不会加载子项的自定义序列化程序。

于 2018-01-10T17:58:31.040 回答
-1

我有同样的问题。有一种方法可以为“parentPage”和“childPages”创建自定义 getter 以避免无限循环。

这样做的唯一条件是您只有 2 个级别的关系,这意味着第一束页面是母版页并且没有其父集,第二束页面是第一束的子页面。

当您需要访问子页面(this.parentPage)的父页面时,您不需要它的子页面。父页面的 getter 只是删除其子页面以避免无限循环。

当您需要访问任何子页面时,您可以通过设置父页面来识别它 - 然后您可以忽略它的子页面并返回 null。

public Page getParentPage() {
    if (this.parentPage != null) {
        // when accessing parent page, we don't need its children
        // as we can get children by accessing page itself
        this.parentPage.childPages = null;
    }
    return this.parentPage;
}

public List<Page> getChildPages() {
    if (this.parentPage != null) {
        // we have parent page set which means this
        // is a child page and we don't need children of children
        return null;
    }
    return this.childPages;
}
于 2019-05-03T22:43:09.660 回答