【发布时间】:2021-12-04 14:34:53
【问题描述】:
我目前正在开发我的项目的搜索和过滤功能。我正在尝试使用此请求正文检索数据:
{
"researchers": [
"Jhon Doe"
],
"unit": null,
"agency":null,
"date": null,
"status": null,
"budget": null
}
以下是 ReasearchRepository 中检索此数据的方法:
@Query("select r from Research r " +
"left join r.fundingAgencies fundingAgencies " +
"left join r.researchers researchers " +
"where (:budgetStart is null or :budgetEnd is null or r.budget between :budgetStart and :budgetEnd )" +
"and (:startDate is null or r.startDate >= :startDate) " +
"and (:endDate is null or r.endDate <= :endDate) " +
"and (:agencyNames is null or fundingAgencies.agencyName in :agencyNames) " +
"and (:unitNames is null or r.deliveryUnit.unitName in :unitNames )" +
"and (:names is null or researchers.name in :names ) " +
"and (:researchStatuses is null or r.researchStatus in :researchStatuses)")
List<Research> findAdvanced( @Param("budgetStart") Double budgetStart,
@Param("budgetEnd") Double budgetEnd,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate,
@Param("agencyNames") Collection<String> agencyNames,
@Param("unitNames") Collection<String> unitNames,
@Param("names") Collection<String> names,
@Param("researchStatuses") Collection<ResearchStatus> researchStatuses);
我的问题是,当我尝试从请求中的给定值中查找数据时,它返回一个空列表 [],即使它存在于数据库中。我想要实现的是,如果参数为null,它会忽略查询中的特定条件,仍然会返回数据。
我刚刚关注了Baeldung的文章。
我还找到了另一篇关于使用 Criteria API 的文章,但我需要很长时间才能理解这一点。我的项目有点赶。
TIA
【问题讨论】:
-
你可以使用
JDBCTemplate,基于非空值构建查询 -
如果我把它集成到我有 Spring Data Jpa 的项目中可以吗?
-
这个 ":paramName is null" 代码看起来是正确的,你在 www.baeldung.com 的文章中做得很好。我认为您的问题不在于这些空条件。
-
它正在工作。我刚刚发现我的服务类有问题。我的代码中有一个修改数据的过程。无论如何,非常感谢您的宝贵时间
标签: java mysql spring spring-boot spring-data-jpa