调用spring数据rest存储库方法不返回链接

我有存储库“ClientRepository”:

public interface ClientRepository extends PagingAndSortingRepository { } 

当我请求http:// localhost:8080 / clients / 1时,服务器响应

 { "algorithmId" : 1, "lastNameTxt" : "***", "firstNameTxt" : "**", "middleNameTxt" : "**", "_links" : { "self" : { "href" : "http://localhost:8080/clients/1121495168" }, "client" : { "href" : "http://localhost:8080/clients/1121495168" } } } 

响应具有预期的链接。

当我在另一个控制器中调用存储库inheritance的方法findOne时

 @RestController public class SearchRestController { @Autowired public SearchRestController(ClientRepository clientRepository) { this.clientRepository = clientRepository; } @RequestMapping(value = "/search", method = RequestMethod.GET) Client readAgreement(@RequestParam(value = "query") String query, @RequestParam(value = "category") String category) { return clientRepository.findOne(Long.parseLong(query)); } } 

它回应

 { "algorithmId" : 1, "lastNameTxt" : "***", "firstNameTxt" : "**", "middleNameTxt" : "**" } 

为什么第二种情况下响应不包含链接? 如何让Spring将它们添加到响应中?

HATEOASfunction仅适用于使用@RepositoryRestResource注释的Spring数据jpa存储库。 这会自动公开其余端点并添加链接。

当您在控制器中使用存储库时,您只需获取对象,jackson映射器将其映射到json。

如果您想在使用Spring MVC控制器时添加链接,请查看此处

为什么第二种情况下响应不包含链接?

因为Spring返回你告诉它返回的内容:一个客户端。

如何让Spring将它们添加到响应中?

在您的控制器方法中,您必须构建Resource 并将其返回。

根据您的代码,以下内容可以满足您的需求:

 @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")); } 

加紧这个,我还建议你:

  • 使用/ clients / search而不是/ search自搜索客户端以来(对RESTful服务更有意义)
  • 使用RepositoryRestController,原因在这里给出

这应该给你一些像:

 @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")); } }