JPA:在 where 子句和 Case 语句中一起使用列表 - 有没有办法循环?

Posted

技术标签:

【中文标题】JPA:在 where 子句和 Case 语句中一起使用列表 - 有没有办法循环?【英文标题】:JPA : Use of list in where clause and Case statement together - Is there a way to loop through? 【发布时间】:2021-11-14 14:11:43 【问题描述】:

我在我们的应用程序中使用 JPA-Hibernate,我正在处理如下查询:

@Query(
value = "ReportDTO(report) FROM Report report " +
    "JOIN p.clientFile cf " +
    "JOIN cf.client cl " +
    "WHERE report.active = TRUE " +
    "AND :companyKey = CASE WHEN report.companyKey IS NOT NULL " +
        "THEN report.companyKey " +
        "ELSE cl.companyKey " +
        "END " +
    "ORDER BY report.publishedDate DESC",
countQuery = “..”
)
@NonNull
Page<TagReportDTO> findAll(@NonNull Pageable pageable, @Param("companyKey") String companyKey);

"companyKey"single 值时,它起作用了。现在,我需要更改此 findAll 方法以接受公司密钥列表。所以它应该像(更改后):

@NonNull
Page<TagReportDTO> findAll(@NonNull Pageable pageable, @Param("companyKeys") List<String> companyKeys);

现在我很难在查询中容纳 对象列表或 companyKeys(而不是 :companyKey case 语句将适用于列表中的每个项目。有什么方法可以循环吗?

【问题讨论】:

【参考方案1】:

您是否尝试过使用 IN 运算符?像这样:

"AND (CASE WHEN report.companyKey IS NOT NULL " +
"THEN report.companyKey " +
"ELSE cl.companyKey " +
"END) IN :companyKeys "

【讨论】:

以上是关于JPA:在 where 子句和 Case 语句中一起使用列表 - 有没有办法循环?的主要内容,如果未能解决你的问题,请参考以下文章

where 子句 oracle 中的 case 语句

使用JPA在Sql中具有不同值的多个语句where子句

where 子句中的 case 语句 - SQL Server

在 where 子句的 Case 语句中定义一个变量

如何使用 case 语句来确定存储过程中的 from 和 where 子句?

在 where 子句 SQL 中的 case 语句中使用参数