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

后端 未结 3 1280
心在旅途
心在旅途 2020-12-28 09:03

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 sta

3条回答
  •  旧巷少年郎
    2020-12-28 09:39

    A simple implementation could look like this:

    @BasePathAwareController
    class CustomInvocationsController implements ResourceProcessor {
    
      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.

提交回复
热议问题