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
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.