带有映射的 RestController 以检索带有或不带 children 的实体
RestController with a mapping to retrieve entity with or without children
我相信这应该很简单,但我似乎不知道该怎么做。
我们有一个实体与另一个实体具有一对多关系。基本 parent/child 关系(使用 Spring/JPA)。
要求是有一个 api '/parents' 提供所有 parents 和另一个 '/parents_with_children' 提供所有 parents 及其相关 child 个实体。
现在要用他们的 children 获得 parents,我们可以指定“@OneToMany(fetch = FetchType.EAGER),这工作正常。
但是,我怎样才能让我的 RestController class 仅 return 没有级联的顶级组件?
// Works fine with eager fetching
@GetMapping("/parents_with_children")
public List<Parent> list() {
return ParentService.getParents();
}
// How can I tell this one to NOT print out the children?
@GetMapping("/parents")
public List<Parent> list() {
return ParentService.getParents();
}
我应该手动打印 & return JSON 来自实体的数据吗?
您可以使用 DTO 模式(简单的 POJO)作为实体的抽象。您可以定义这些 ParentDto
并在 JSON.
中创建您想要 return 的所有方法
想法是从数据库中获取您的实体,将其映射到 DTO。在没有 children 的 /parents 的情况下,您根本不会设置 children 列表(将其保留为空)。
然后您可以用 @JsonInclude(JsonInclude.Include.NON_NULL)
标记该字段,如果设置了该字段,它将仅在 JSON 中显示该字段。
public class ParentDto {
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<Children> children;
// other private members
// getters/setters
}
有一些库可以为您进行映射,例如 mapstruct
或 ModelMapper
,或者您可以自己将 Parent
实体映射到 ParentDto
。
然后你的控制器会return DTO。
public List<ParentDto> list();
我相信这应该很简单,但我似乎不知道该怎么做。
我们有一个实体与另一个实体具有一对多关系。基本 parent/child 关系(使用 Spring/JPA)。
要求是有一个 api '/parents' 提供所有 parents 和另一个 '/parents_with_children' 提供所有 parents 及其相关 child 个实体。
现在要用他们的 children 获得 parents,我们可以指定“@OneToMany(fetch = FetchType.EAGER),这工作正常。
但是,我怎样才能让我的 RestController class 仅 return 没有级联的顶级组件?
// Works fine with eager fetching
@GetMapping("/parents_with_children")
public List<Parent> list() {
return ParentService.getParents();
}
// How can I tell this one to NOT print out the children?
@GetMapping("/parents")
public List<Parent> list() {
return ParentService.getParents();
}
我应该手动打印 & return JSON 来自实体的数据吗?
您可以使用 DTO 模式(简单的 POJO)作为实体的抽象。您可以定义这些 ParentDto
并在 JSON.
想法是从数据库中获取您的实体,将其映射到 DTO。在没有 children 的 /parents 的情况下,您根本不会设置 children 列表(将其保留为空)。
然后您可以用 @JsonInclude(JsonInclude.Include.NON_NULL)
标记该字段,如果设置了该字段,它将仅在 JSON 中显示该字段。
public class ParentDto {
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<Children> children;
// other private members
// getters/setters
}
有一些库可以为您进行映射,例如 mapstruct
或 ModelMapper
,或者您可以自己将 Parent
实体映射到 ParentDto
。
然后你的控制器会return DTO。
public List<ParentDto> list();