2

I have created a custom controller which needs to convert entities to resources. I have annotated my repositories with @RepositoryRestResource annotation. I want to know if there is a way I can invoke the default functionality of spring Data REST from my custom controller which serializes the entities to resources with links to other entities embedded in them.

I don't want to return entities from my handler method but Resources.

Thanks.

Abdul Fatah
  • 463
  • 6
  • 23

1 Answers1

3

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.

Cepr0
  • 28,144
  • 8
  • 75
  • 101