实现 Spring Data 存储库的自定义方法并通过 REST 公开它们 [英] Implementing custom methods of Spring Data repository and exposing them through REST

查看:25
本文介绍了实现 Spring Data 存储库的自定义方法并通过 REST 公开它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将自定义方法添加到我的 Spring 数据存储库 PersonRepository,如 1.3 Spring Data 存储库的自定义实现 并通过 REST 公开这些方法.初始代码来自 Accessing JPA Data with REST 示例,这里是添加/修改类的代码:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆