gpt4 book ai didi

java - 调用 Spring Data Rest Repository 方法不返回链接

转载 作者:行者123 更新时间:2023-12-01 21:26:16 25 4
gpt4 key购买 nike

我有存储库“ClientRepository”:

public interface ClientRepository extends PagingAndSortingRepository<Client, Long> {
}

当我请求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"
}
}
}

响应具有预期的链接。

当我在另一个 Controller 中调用存储库继承的方法 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 将它们添加到响应中?

最佳答案

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

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

What to do to make Spring add them to response?

在你的 Controller 方法中,你必须构建 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,原因如下 here

这应该给你类似的东西:

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

关于java - 调用 Spring Data Rest Repository 方法不返回链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36335951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com