【问题标题】:Spring Boot REST application; findBy method using foreign keySpring Boot REST 应用程序;使用外键的 findBy 方法
【发布时间】:2020-07-08 21:37:23
【问题描述】:

使用 Spring Data REST,我有两个模型,NvdApps 与 NvdVulnerabilities 具有一对多关系

我正在尝试添加通过 NvdApp 搜索 NvdVulnerabilities 的功能,因此我的存储库如下所示:

public interface NvdVulnerabilityRepository extends PagingAndSortingRepository<NvdVulnerability, Long> {
    List<NvdVulnerability> findByNvdApp(NvdApp nvdApp);
}

这给了我 REST 端点:

"findByNvdApp" : {
      "href" : "http://localhost:8080/api/nvdVulnerabilities/search/findByNvdApp{?nvdApp}",
      "templated" : true
    }

当我尝试使用这个端点时,它只会返回整个表,而不管我在查询字符串中输入了什么。我尝试过的示例 URL:

http://localhost:8080/api/nvdVulnerabilities/search/findByNvdApp?nvd_app_id=25
http://localhost:8080/api/nvdVulnerabilities/search/findByNvdApp?25
http://localhost:8080/api/nvdVulnerabilities/search/findByNvdApp?NvdApp=25

我是否缺少一些配置?我基本上是在尝试复制查询:

SELECT * FROM NVD_VULNERABILITY where nvd_app_id = 25

在 H2 数据库控制台中按预期工作。搜索端点究竟是如何工作的,如何让它按预期过滤?

我还想让分页与搜索端点一起工作;现在它返回整个 7k+ 行,而端点 http://localhost:8080/api/nvdVulnerabilities/ 每页返回 20 个项目

【问题讨论】:

    标签: java spring spring-boot spring-data-rest


    【解决方案1】:

    你可以试试:

    List<NvdVulnerability> findByNvdApp_Id(Integer id);
    

    如果Integer id 变量存在于您的NvdApp 类中。

    【讨论】:

    • 好的,这确实有效。有什么方法也可以启用分页吗?
    • 想通了,将其添加到我的问题中,感谢您的帮助
    【解决方案2】:

    更改存储库查询以匹配以下内容:

    public interface NvdVulnerabilityRepository extends PagingAndSortingRepository<NvdVulnerability, Long> {
        Page<NvdVulnerability> findByNvdApp_Id(Long id, Pageable pageable);
    }
    

    允许按 id 搜索以及使返回分页

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 2016-11-06
      • 2017-04-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2015-04-06
      • 2014-09-12
      • 1970-01-01
      相关资源
      最近更新 更多