【问题标题】:JPA NamedQuery - Ignore Line when passed field is nullJPA NamedQuery - 当传递的字段为空时忽略行
【发布时间】:2018-10-25 12:29:22
【问题描述】:

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

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

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

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)"

【问题讨论】:

    标签: spring hibernate jpa entitymanager named-query


    【解决方案1】:
    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);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2014-09-27
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多