Very simple, using objects Resource
or Resources
. For example - in this controller we add custom method which return list of all user roles which are enums:
@RepositoryRestController
@RequestMapping("/users/roles")
public class RoleController {
@GetMapping
public ResponseEntity<?> getAllRoles() {
List<Resource<User.Role>> content = new ArrayList<>();
content.addAll(Arrays.asList(
new Resource<>(User.Role.ROLE1),
new Resource<>(User.Role.ROLE2)));
return ResponseEntity.ok(new Resources<>(content));
}
}
To add links to resource you have to use object RepositoryEntityLinks
, for example:
@RequiredArgsConstructor
@RepositoryRestController
@RequestMapping("/products")
public class ProductController {
@NonNull private final ProductRepo repo;
@NonNull private final RepositoryEntityLinks links;
@GetMapping("/{id}/dto")
public ResponseEntity<?> getDto(@PathVariable("id") Integer productId) {
ProductProjection dto = repo.getDto(productId);
return ResponseEntity.ok(toResource(dto));
}
private ResourceSupport toResource(ProductProjection projection) {
ProductDto dto = new ProductDto(projection.getProduct(), projection.getName());
Link productLink = links.linkForSingleResource(projection.getProduct()).withRel("product");
Link selfLink = links.linkForSingleResource(projection.getProduct()).slash("/dto").withSelfRel();
return new Resource<>(dto, productLink, selfLink);
}
}
For more example see my 'how-to' and sample project.