Calling spring data rest repository method doesn't return links

↘锁芯ラ 提交于 2019-12-02 01:08:41

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

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"));
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!