在自定义@RepositoryRestController方法中填充实体链接
我使用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); }
我希望输出能够像spring-data-rest控制器的任何其他响应一样得到丰富,特别是我希望它将HATEOAS链接添加到它自身及其关系中。
最近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 post( @RequestBody MyEntity entity, PersistentEntityResourceAssembler resourceAssembler)) { List myEntities = ... List<> resources = myEntities .stream() .map(resourceAssembler::toResource) .collect(Collectors.toList()); return new Resources(resources); }
最后,对于分页响应,应该使用注入的PagedResourcesAssembler,传入方法注入的ResourceAssembler和Page,而不是实例化Resources。 有关如何使用PersistentEntityResourceAssembler
和PagedResourcesAssembler
更多详细信息,请PagedResourcesAssembler
此答案 。 请注意,目前这需要使用原始类型和未经检查的强制转换。
可能有自动化的空间,欢迎更好的解决方案。
PS:我还创建了一个JIRA票证 ,将其添加到Spring Data的文档中。