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

Filling entity links in custom @RepositoryRestController methods

我正在使用 Spring-data-rest 为某些 JPA 实体提供读取 API。 对于写入,我需要发出命令对象而不是直接写入数据库,因此我使用 @RepositoryRestController 和各种命令处理方法添加了自定义控制器:

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody MyEntity post(@RequestBody MyEntity entity) {
  String createdId = commands.sendAndWait(new MyCreateCommand(entity));
  return repo.findOne(createdId);
}

我希望输出像 spring-data-rest 控制器的任何其他响应一样丰富,特别是我希望它向自身及其关系添加 HATEOAS 链接。

最近 (see point 3.) by Oliver Gierke 他本人(虽然这个问题使用了完全不同的关键字,所以我不会将其标记为重复)。

单个实体的示例将变为:

@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 和页面,而不是实例化资源。有关如何使用 PersistentEntityResourceAssemblerPagedResourcesAssembler 的更多详细信息,请参阅 this answer。请注意,目前这需要使用原始类型和未经检查的转换。

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

P.S.: 我还创建了一个 JIRA ticket 将其添加到 Spring 数据的文档中。