尝试使用Spring HATEOAS链接到JPA Repository查询方法并获取IllegalArgumentException:'uriTemplate'不能为null

问题描述 投票:0回答:1

在我的应用程序中,我在Things和Stuff之间有一个外键关系,其中给定的Thing可能包含数百个Stuffs,而我正在使用Spring Data JPA来暴露Thing和Stuff存储库。

我想显示与用户选择Thing相关的所有Stuff,但由于返回的大小我想要分页Stuff结果。

搜索显示无法从Thing返回的嵌入式东西链接添加分页功能,因此从我的Thing存储库返回的以下链接永远不会被分页:

"stuff": {
    "href": "http://localhost:8080/api/things/1/stuff"
}

所以我已经在我的Stuff存储库中添加了一个自定义方法来获取所有Stuff by thing Id,并且在直接调用时工作正常。

我想添加指向自定义搜索方法的Thing Resource返回的链接以获取所有关联的Stuff,但是当我使用ControllerLinkBuilder.linkTo()方法时它失败了

java.lang.IllegalArgumentException: 'uriTemplate' must not be null
at org.springframework.util.Assert.hasText(Assert.java:181) ~[spring-core-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.web.util.UriTemplate.<init>(UriTemplate.java:61) ~[spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]

东西回购:

public interface StuffRepo extends JpaRepository<Stuff, Long> {

    Page<Stuff> findByThingId(@Param("thingId") Long thingId, Pageable pageable);
}

组态:

@Bean
ThingProcessor getThingProcessor()
{
    return new ThingProcessor();
}

public static class ThingProcessor implements ResourceProcessor<Resource<Thing>>{
    @Override
    public Resource<Thing> process(Resource<Thing> resource) {
        ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(StuffRepo.class).findByThingId(resource.getContent().id, null));
        return resource;
    }
}

我错过了一些注释或配置吗?我试过用@RestResource注释Repo和方法,但没有区别。还有更好的方法来获取子对象的分页结果吗?

java spring spring-data-rest spring-hateoas
1个回答
0
投票

我使用RepositoryEntityLinks类来解决这个问题,它给你一个Link对象的列表,从那里我找到了我需要使用的link.getRel()

© www.soinside.com 2019 - 2024. All rights reserved.