最近,Oliver Gierke亲自回答了这个问题(请参见第3点)(尽管问题使用了完全不同的关键字,所以我不会将其标记为重复)。
单个实体的示例将变为:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody PersistentEntityResource post(@RequestBody MyEntity entity,
PersistentEntityResourceAssembler resourceAssembler)) {
String createdId = commands.sendAndWait(new MyCreateCommand(entity));
return resourceAssembler.toResource(repo.findOne(createdId));
}
非分页列表的示例:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Resources<PersistentEntityResource> post(
@RequestBody MyEntity entity,
PersistentEntityResourceAssembler resourceAssembler)) {
List<MyEntity> myEntities = ...
List<> resources = myEntities
.stream()
.map(resourceAssembler::toResource)
.collect(Collectors.toList());
return new Resources<PersistentEntityResource>(resources);
}
最后,对于分页响应,应该使用注入的PagedResourcesAssembler,传入方法注入的ResourceAssembler和Page,而不是实例化Resources。有关如何使用的更多细节PersistentEntityResourceAssembler
,并PagedResourcesAssembler
可以发现这个答案。请注意,目前这需要使用原始类型和未检查的强制类型转换。