我们如何让 spring-data-rest 为查询返回单个资源,而不是嵌入列表?这将使客户的导航更加直观。
例如
t.follow("search", "byNameAndType", "identity", "mainContact")
代替
t.follow("search", "byNameAndType", "$_embedded.credentials[0]._links.identity.href", "mainContact")
我有一个始终返回 1 或 0 结果的 JPA 存储库。唯一性由数据库约束强制执行。
@RepositoryRestResource
public interface CredentialRepository extends PagingAndSortingRepository<Credential, Long>,
ExternalIdRepository<Credential, Long> {
@RestResource(path = "byNameAndType", rel = "byNameAndType")
Credential findByNameIgnoreCaseAndTypeIgnoreCase(@Param("name") String name, @Param("type") String type);
}
spring-data-rest 不是返回单个凭证对象,而是返回一个嵌入式列表。
$ curl -H "Accept: text/plain, application/hal+json, */*" -H "X-VCIDB-User-Id:testUser" http://127.0.0.1:8090/credentials/search/byNameAndType?name=V6UqkSG8\&type=myType
{
"_embedded" : {
"credentials" : [ {
"version" : 1,
"lastUpdTs" : "2014-11-13T12:08:49.301+13:00",
"lastUpdBy" : ":integration-test",
"createdTs" : "2014-11-13T12:08:49.092+13:00",
etc etc
相反,它应该返回与我通过主键检索它一样的返回值。
{
"version" : 1,
"lastUpdTs" : "2014-11-13T12:08:49.301+13:00",
etc etc
否则客户端的 API 看起来很糟糕
Traverson t = new Traverson(new URI("http://127.0.0.1:8090/credentials"), MediaTypes.HAL_JSON);
t.setRestOperations(template);
Map<String, Object> params = new HashMap<>();
params.put("name", "V6UqkSG8");
params.put("type", "myType");
String contactUuid = t.follow("search", "byNameAndType", "$_embedded.credentials[0]._links.identity.href", "mainContact")
.withTemplateParameters(params).<String> toObject("$.uuid");
LOG.info(contactUuid);
assertThat(contactUuid, Matchers.is("7a7faeaf-6da3-4188-9d28-afbb30ce38b3"));
如果是以下情况,那么对于客户端来说,遍历会更容易理解:
String contactUuid = t.follow("search", "byNameAndType", "identity", "mainContact")
.withTemplateParameters(params).<String> toObject("$.uuid");