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

后端 未结 3 1284
心在旅途
心在旅途 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:58

    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, ResourceAssembler> {
    
        @Autowired
        private PersonRepository repository;
    
        @Autowired
        private EntityLinks entityLinks;
    
        @RequestMapping(value = "/lookup", method = RequestMethod.GET)
        public ResponseEntity> lookup(@RequestParam("name") String name)
        {
            try
            {
              Resource resource = toResource(repository.lookup(name));
              return new ResponseEntity>(resource, HttpStatus.OK);
            }
            catch (PersonNotFoundException nfe)
            {
                return new ResponseEntity>(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 toResource(Person person) {
            Resource resource = new Resource(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.

提交回复
热议问题