我用JHipster生成了一个简单的应用程序。我有几个关系中的实体。例如,我有一个IndexPage
,其中包含几个IndexAreas
。每个IndexArea
可以包含几个IndexTiles
。每个IndexTile
连接到一个CoursePage
。
默认情况下,我在@JsonIgnore
侧面有@OneToMany
注释,但这意味着我无法显示前端的所有元素(因为我没有看到它们)。例如,我可以编辑一个IndexTile
并从下拉列表中选择一个IndexArea
,但我不能通过ng-repeat
中的IndexTiles
执行IndexArea
,因为它们不在JSON中。
如果我删除@JsonIgnore
,我会得到一个无限递归(这是预期的)。所以我用@JsonIgnore
替换了所有的@JsonSerialize(using = MyCustomSerializer.class)
s。这是我目前的状态:
public class IndexPage {
...
@OneToMany(mappedBy = "indexPage")
@JsonSerialize(using = IndexAreaSerializer.class)
private Set<IndexArea> indexAreas = new HashSet<>();
...
}
public class IndexArea {
...
@ManyToOne
private IndexPage indexPage;
@OneToMany(mappedBy = "indexArea")
@JsonSerialize(using = IndexTileSerializer.class)
private Set<IndexTile> indexTiles = new HashSet<>();
...
}
public class IndexTile{
...
@ManyToOne
private IndexArea indexArea;
@OneToOne
@JoinColumn(unique = true)
private CoursePage coursePage;
...
}
public class CoursePage {
...
@OneToOne(mappedBy = "coursePage")
@JsonIgnore // a CoursePage doesn't care about the indexTile
private IndexTile indexTile;
...
}
现在当我刷新页面时,我收到一个错误:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: rs.kursnemackog.domain.IndexPage.indexAreas, could not initia
lize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: rs.kursnemackog.domain.IndexPage.indexAreas, could no
t initialize proxy - no Session (through reference chain: rs.kursnemackog.domain.IndexPage["indexAreas"])
为了能够看到关系的两面并且正常使用它们,我能做些什么(例如,能够通过某个IndexArea
中的所有IndexTile
为ng-repeat
和IndexTiles
选择IndexArea
)?
谢谢。
延迟加载异常是正常的,因为JHipster将所有关系声明为延迟加载,这被认为是一种很好的做法。该异常是由于缺少会话,因为它是在JSON序列化时完成的,因此在服务或存储库层中关闭了事务之后。
有几种解决方案,比如使用@Transactional
或open-session-in-view
属性扩展事务范围,但通常更好的是使用@EntityGraph
或查询语言修改存储库以急切获取关系。
更多提示:How does the FetchMode work in Spring Data JPA
此外,您可能希望在JHipster中使用DTO和Service类选项,以避免在REST API中公开您的实体,并获得对Angular应用程序所使用的对象的更多控制。