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

And*_*tto 7 java spring jpa spring-data-rest spring-hateoas

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

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

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

hzp*_*zpz 13

最近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));
}
Run Code Online (Sandbox Code Playgroud)

非分页列表的示例:

@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);
}
Run Code Online (Sandbox Code Playgroud)

最后,对于分页响应,应该使用注入的PagedResourcesAssembler,传入方法注入的ResourceAssembler和Page,而不是实例化Resources.有关如何使用的更多详细信息PersistentEntityResourceAssembler,PagedResourcesAssembler可以在此答案中找到.请注意,目前这需要使用原始类型和未经检查的强制转换.

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

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