您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在自定义@RepositoryRestController方法中填充实体链接

在自定义@RepositoryRestController方法中填充实体链接

最近,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可以发现这个答案。请注意,目前这需要使用原始类型和未检查的强制类型转换。

可能还有自动化的空间,欢迎更好的解决方案。

PS:我还创建了JIRA票证,将其添加到Spring Data的文档中。

其他 2022/1/1 18:29:40 有399人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶