在Spring Data JPA documentation中,它解释了如何使用PagedResourcesAssembler生成链接。该文档引用了toResources()方法,但据我所知,该方法不存在。我已经成功生成了资源集合的链接,但我无法弄清楚如何为子资源生成链接。
这是我的控制器:
public HttpEntity<PagedResources<Party>> search(@RequestBody PartySearchRequest request,
Pageable pageable, PagedResourcesAssembler<Party> assembler ) {
Map<String,String> searchFilters = RequestValidator.validateContractSearchFilters(request);
Page<Party> parties = repository.findByFirstNameOrLastName(searchFilters.get("firstName"), searchFilters.get("lastName"), pageable);
return new ResponseEntity(assembler.toResource(parties), HttpStatus.OK);
}
这会生成以下JSON:
{
"_embedded": {
"partyList": [
{
"firstNm": "John",
"lastNm": "Doe",
},
{
"firstNm": "Bob",
"lastNm": "Smith",
}
],
}
]
},
"_links": {
"first": {
"href": "http://localhost:8080/v1/party/search?page=0&size=2"
},
"self": {
"href": "http://localhost:8080/v1/party/search?page=0&size=2"
},
"next": {
"href": "http://localhost:8080/v1/party/search?page=1&size=2"
},
"last": {
"href": "http://localhost:8080/v1/party/search?page=7&size=2"
}
},
"page": {
"size": 2,
"totalElements": 16,
"totalPages": 8,
"number": 0
}
}
正如您所看到的,我获得了整个聚会搜索的链接,但没有获得各个聚会对象的链接。 (我认为我的问题类似于这个问题:How to add HATEOAS links in a sub resource)但我不太确定,所以我发布了自己的问题。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:1)
您需要扩展ResourceAssemblerSupport的类的引用。
这应该有效,将myResourceAssembler更改为您的类:
在您的控制器中:
private final MyResourceAssembler myResourceAssembler;
public MyController(MyResourceAssembler myResourceAssembler) {
this.myResourceAssembler = myResourceAssembler;
}
public HttpEntity<PagedResources<Party>> search(@RequestBody PartySearchRequest request,
Pageable pageable, PagedResourcesAssembler<Party> assembler ) {
Map<String,String> searchFilters = RequestValidator.validateContractSearchFilters(request);
Page<Party> parties = repository.findByFirstNameOrLastName(searchFilters.get("firstName"), searchFilters.get("lastName"), pageable);
Link selfLink = linkTo(methodOn(this.getClass().view(pageable, null)).withSelfRel();
return new ResponseEntity(assembler.toResource(parties, myResourceAssembler, selfLink), HttpStatus.OK);
}
而且,如果你不想要自我链接:
return new ResponseEntity(assembler.toResource(parties, myResourceAssembler), HttpStatus.OK);