Filling entity links in custom @RepositoryRestController methods

痴心易碎 提交于 2019-12-03 07:50:02

问题


I am using Spring-data-rest to provide read APIs over some JPA entities. For writes I need to issue Command objects rather than directly write to the DB, so I added a custom controller using @RepositoryRestController and various command handling methods:

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

I would like the output to be enriched just like any other response by the spring-data-rest controller, in particular I want it to add HATEOAS links to itself and its relations.


回答1:


This has recently been answered (see point 3.) by Oliver Gierke himself (the question used quite different keywords though, so I won't flag this as duplicate).

The example for a single entity would become:

@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));
}

The example for a non-paginated listing:

@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);
}

Finally, for a paged response one should use an injected PagedResourcesAssembler, passing in the method-injected ResourceAssembler and the Page, rather than instantiating Resources. More details about how to use PersistentEntityResourceAssembler and PagedResourcesAssembler can be found in this answer. Note that at the moment this requires to use raw types and unchecked casts.

There is room for automation maybe, better solutions are welcome.

P.S.: I also created a JIRA ticket to add this to Spring Data's documentation.



来源:https://stackoverflow.com/questions/31924980/filling-entity-links-in-custom-repositoryrestcontroller-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!