Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom methods to Spring Data Rest JPA implementation and leverage HATEOS support?

I have a Spring Data Rest Repository controller that utilizes JPA for the query implementation, and I need to add some custom query methods that cannot be done using the standard queryByExample method that JPA supports. I have created an Impl class that has the necessary method, but I cannot get it to be recognized. I saw that I can utilize a standard Spring MVC Controller, but I want to have a unified API, and basically all I really want is to implement my own custom /search methods.

Even with the custom controller, the problem is then that the HAL links and other related items are no longer provided.

Can the Spring folks spend some time having someone document how to do some of this more advanced stuff? I'm guessing that having to implement your own search methods at times are fairly common, and it would be time well spent to make it clear how to do this.

like image 835
Marc Zampetti Avatar asked Apr 10 '15 21:04

Marc Zampetti


1 Answers

A simple implementation could look like this:

@BasePathAwareController
class CustomInvocationsController implements ResourceProcessor<RepositorySearchesResource> {

  private final YourRepository repository;

  public CustomInvocationsController(YourRepository repository) {
    this.repository = repository;
  }

  @RequestMapping(…)
  ResponseEntity<?> handleRequest(PersistentEntityResourceAssembler assembler)

    // invoke repository
    // Use assembler to build a representation
    // return ResponseEntity
  }

  @Override
  public RepositorySearchesResource process(RepositorySearchesResource resource) {
    // add Link to point to the custom handler method
  }
}

A few things to note:

  • using @BasePathAwareController instead of a plain @Controller makes sure whatever you're mapping the handler method to, it will consider the base path you've configured on Spring Data REST, too.
  • within the request mapping, use everything you already know from Spring MVC, choose an appropriate HTTP method.
  • PersistentEntityResourceAssembler basically abstracts setting up a representation model within a PersistentEntityResource so that the Spring Data REST specific treatment of associations etc. kicks in (associations becoming links etc.
  • implement ResourceProcessor to post-process RepositorySearchesResource which is returned for the resource rendering all searches. Currently, there's no way to determine which domain type that resource was rendered. I filed and fixed DATAREST-515 to improve that.
like image 155
Oliver Drotbohm Avatar answered Sep 17 '22 13:09

Oliver Drotbohm