实现Spring Data存储库的自定义方法并通过REST公开它们 [英] Implementing custom methods of Spring Data repository and exposing them through REST
问题描述
我正在尝试将自定义方法添加到我的Spring Data存储库 PersonRepository
,如 1.3 Spring Data存储库的自定义实现并通过REST公开这些方法。初始代码来自使用REST访问JPA数据示例,以下是添加/修改类的代码:
I'm trying to add custom methods to my Spring Data repository PersonRepository
as described in 1.3 Custom implementations for Spring Data repositories and exposing these method through REST. The initial code is from Accessing JPA Data with REST sample, here is the code for added/modified classes:
interface PersonRepositoryCustom {
List<Person> findByFistName(String name);
}
class PersonRepositoryImpl implements PersonRepositoryCustom, InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// initialization here
}
@Override
public List<Person> findByFistName(String name) {
// find the list of persons with the given firstname
}
}
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(@Param("name") String name);
}
当我运行应用程序并访问 http:/ / localhost:8080 / portfolio / search /
,我得到以下回复正文:
When I run the application and visit http://localhost:8080/portfolio/search/
, I get the following response body:
{
"_links" : {
"findByLastName" : {
"href" : "http://localhost:8080/people/search/findByLastName{?name}",
"templated" : true
}
}
}
为什么 findByFirstName
即使在 PersonRepository
界面中可用,也不会公开?
Why findByFirstName
is not exposed even if it is available in the PersonRepository
interface?
另外,有没有办法动态/编程地添加要通过REST公开的存储库?
Also, is there a way to dynamically/programmatically add respositories to be exposed via REST?
推荐答案
这些原因这些没有暴露的方法是你基本上可以自由地在自定义存储库方法中实现任何你想要的东西,因此不可能推断出支持该特定资源的正确HTTP方法。
The reason these methods are not exposed is that you're basically free to implement whatever you want in custom repository methods and thus it's impossible to reason about the correct HTTP method to support for that particular resource.
在您的情况下,使用可能没问题一个简单的 GET
,在其他情况下,它可能必须是 POST
,因为该方法的执行有副作用。
In your case it might be fine to use a plain GET
, in other cases it might have to be a POST
as the execution of the method has side effects.
目前的解决方案是制作一个自定义控制器来调用存储库方法。
The current solution for this is to craft a custom controller to invoke the repository method.
这篇关于实现Spring Data存储库的自定义方法并通过REST公开它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!