使用 Spring Data Core 中的 PagedResourcesAssembler 生成 HATEOAS link

Using PagedResourcesAssembler from Spring Data Core for HATEOAS link generation

在 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)但我不太确定所以我发布了自己的问题。

如有任何帮助,我们将不胜感激!谢谢!

您需要对扩展 ResourceAssemblerSupport 的 class 的引用。

这应该有效,将 myResourceAssembler 更改为您的 class 是:

在你的控制器中:

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);

}

而且,如果您不想要 selfLink:

return new ResponseEntity(assembler.toResource(parties, myResourceAssembler), HttpStatus.OK);

参考资料