Filling entity links in custom @RepositoryRestController methods

后端 未结 1 2094
挽巷
挽巷 2021-02-03 13:48

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 con

1条回答
  •  清歌不尽
    2021-02-03 14:26

    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 post(
        @RequestBody MyEntity entity,
        PersistentEntityResourceAssembler resourceAssembler)) {
      List myEntities = ...
      List<> resources = myEntities
          .stream()
          .map(resourceAssembler::toResource)
          .collect(Collectors.toList());
      return new Resources(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.

    0 讨论(0)
提交回复
热议问题