Calling spring data rest repository method doesn't return links

后端 未结 2 1563

I have the repository \"ClientRepository\":

public interface ClientRepository extends PagingAndSortingRepository {
}

When i

相关标签:
2条回答
  • 2021-01-22 03:09

    The HATEOAS functionality is available out of the box only for the Spring data jpa repositories annotated with @RepositoryRestResource. That automatically exposes the rest endpoint and adds the links.

    When you use the repository in the controller you just get the object and the jackson mapper maps it to json.

    If you want to add links when using Spring MVC controllers take a look here

    0 讨论(0)
  • 2021-01-22 03:21

    Why doesn't response contain links in the second case?

    Because Spring returns what you tell it to return: a Client.

    What to do to make Spring add them to response?

    In your controller method, you have to build Resource<Client> and return it.

    Based on your code, the following should get you what you want:

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    Client readAgreement(@RequestParam(value = "query") String query,
                         @RequestParam(value = "category") String category) {
        Client client = clientRepository.findOne(Long.parseLong(query));
        BasicLinkBuilder builder = BasicLinkBuilder.linkToCurrentMapping()
                                                   .slash("clients")
                                                   .slash(client.getId());
        return new Resource<>(client,
                              builder.withSelfRel(),
                              builder.withRel("client"));
    }
    

    Stepping up from this, I would also suggest you to:

    • use /clients/search rather than /search since your search for a client (makes more sense for a RESTful service)
    • use a RepositoryRestController, for reasons given here

    That should give you something like:

    @RepositoryRestController
    @RequestMapping("/clients")
    @ResponseBody
    public class SearchRestController {
    
        @Autowired
        private ClientRepository clientRepository;
    
        @RequestMapping(value = "/search", method = RequestMethod.GET)
        Client readAgreement(@RequestParam(value = "query") String query,
                             @RequestParam(value = "category") String category) {
            Client client = clientRepository.findOne(Long.parseLong(query));
            ControllerLinkBuilder builder = linkTo(SearchRestController.class).slash(client.getId());
    
            return new Resource<>(client,
                    builder.withSelfRel(),
                    builder.withRel("client"));
        }
    }
    
    0 讨论(0)
提交回复
热议问题