JPA NamedQuery - 当传递的字段为空时忽略行

JPA NamedQuery - Ignore Line when passed field is null

所以我有一个 NamedQuery,其中的字段是通过 enityManager.createNamedQuery 从 Repo 传递的。

所以我有两个字段,areaId 和 fieldId,areaId 将始终存在,但 fieldId 有时会为空。

如果 :fieldId 为 null,如何省略(删除)以下行

and summary.bucket.fieldId.id = :fieldId --line to be removed

以下是我尝试使用的案例场景,但它不起作用。

我愿意接受最好的方法或指导吗?

 @NamedQuery(name = "SummaryBySubstatus.getInfo",
            query = "select new com.model.group.summaryGroup(summary.bucket.area.id,"
                    summary.bucket.facilityProductInfo,
                    from SummaryBySubstatus as summary
                    where summary.bucket.area.id = :areaId
                    and summary.bucket.fieldId.id = :fieldId
                    ---Tried This way---
                    and(case when :fieldId != null then summary.bucket.fieldId.id = :fieldId end)"
and summary.bucket.fieldId.id = :fieldId

fieldId 在合规数据库(不是 MySQL)上为空时,这将始终评估为 false。尝试

where summary.bucket.area.id = :areaId
and ( :fieldId IS NOT NULL AND summary.bucket.fieldId.id = :fieldId
or :fieldId IS NULL AND summary.bucket.fieldId.id = :fieldId )

如果您使用的是 PostgreSQL,则需要调用

来绕过一个错误
query.setParameter("fieldId", not_null_value_of_the_same_type);
query.setParameter("fieldId", the_real_value_that_can_be_null);

或者您可以只创建两个查询。