我们如何使spring-data-rest为查询返回单个资源,而不是嵌入列表?这将使客户端的导航更加直观。
e.g。
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"));
当客户端的transversion更容易理解时:
String contactUuid = t.follow("search", "byNameAndType", "identity", "mainContact")
.withTemplateParameters(params).<String> toObject("$.uuid");