12
votes

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.

3
The easiest approach is to define custom JPQL queries using @Query annotations on methods defined by the Repository interface. This article provides the details. Personally I don't like this approach since you are forced to use verbs (e.g. /resource/search/findByCustom) which is not RESTful; so I created my own search controller and used some of the Spring Data Rest Components to properly integrate with the rest of the Resources (ping me you want more details) - dimi
@dimi You are not forced to use verbs. But even if you choose to use "findByX" then it's only a search with the name "findByX". It is a resource and it is RESTful. - a better oliver
@zeroflagL I agree you don't have to use findByX names, but in Java: "By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb". Exposing them directly under the /search sub-resource you end up creating multiple methods on the same Resource which look more like verbs (or actions) than nouns; this is not good since this is what HTTP methods should be used for: actions. Instead, my preference is to use the HTTP query part of the Resource URL to define the filtering criteria: http://..../resource?q=name:somename&page=1&size=10 - dimi
@dimi The JDK contains plenty of methods that don't follow that pattern. The Java architects themselves even recommend something like users alongside getUsers to additionally support a Stream return type. But even if you name your method findByX it doesn't mean that you have to name the resource findByX too. You can have findByName while exposing it as /users/search/foo. You are arguing that a renowned framework supporting the highest level of REST is not RESTful. Think about it. Btw: There are experts who would discourage ?q=name:somename. - a better oliver
@zeroflagL I'm not arguing Spring Data REST is not RESTful..I think it's absolutely awesome! I'm arguing with your note that findByX is a Resource..it does not look as such. I also don't like that Data REST recommends using (and exposing) findByX methods in it's guides. Wrt the method names, there can be exceptions yes, but the intuition and good practice is to use verbs or something that defines an action. Good point that you can expose the repository methods under different paths that look more like Resources; I give you that. - dimi

3 Answers

11
votes

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

Ok, based upon the information provided so far, I have something working that I think makes sense. I'm definitely looking for someone to validate my theories so far.

The goal was to be able to implement additional custom methods to the methods that SDR already provides. This is because I need to implement additional logic that cannot be expressed as simple Spring Data Repository query methods (the findByXXX methods). In this case, I'm looking to query other data sources, like Solr, as well as provide custom manipulation of the data before its returned.

I have implemented a Controller based upon what @oliver suggested, as follows:

@BasePathAwareController
@RequestMapping(value = "/persons/search")
public class PersonController implements ResourceProcessor<RepositorySearchesResource>, ResourceAssembler<Person, Resource<Person>> {

    @Autowired
    private PersonRepository repository;

    @Autowired
    private EntityLinks entityLinks;

    @RequestMapping(value = "/lookup", method = RequestMethod.GET)
    public ResponseEntity<Resource<Person>> lookup(@RequestParam("name") String name)
    {
        try
        {
          Resource<Person> resource = toResource(repository.lookup(name));
          return new ResponseEntity<Resource<Person>>(resource, HttpStatus.OK);
        }
        catch (PersonNotFoundException nfe)
        {
            return new ResponseEntity<Resource<Person>>(HttpStatus.OK);
        }
    }

    @Override
    public RepositorySearchesResource process(RepositorySearchesResource resource) {

        LinkBuilder lb = entityLinks.linkFor(Person.class, "name");
        resource.add(new Link(lb.toString() + "/search/lookup{?name}", "lookup"));
        return resource;
    }

    @Override
    public Resource<Person> toResource(Person person) {
        Resource<IpMaster> resource = new Resource<Person>(person);

        return resource;
    }

This produces a "lookup" method that is considered a template and is listed when you do a query on /persons/search, along with the other search methods defined in the Repository. It doesn't use the PersistentEntityResourceAssembler that was suggested. I think I would rather use that, but then I'm a bit confused as to how to get it injected, and what the comment about the filed bug means.

0
votes

See the latest docs, as the most recent version of SDR has more details on this, and makes it a bit easier. The key is to use the @RepositoryRestController annotation to be able to add additional methods under the /search endpoint, or the @BasePathAwareController annotation if you want to add endpoints to other parts of the url namespace. Then include the PersistentEntityResourceAssembler as a parameter to your controller method, and use that to generate the HAL output if you are returning your entity objects.