【问题标题】:HQL doesn't extract results with null fieldsHQL 不提取空字段的结果
【发布时间】:2016-03-14 16:30:44
【问题描述】:

我想使用 HQL 从表中检索所有元组,即使包含空字段。逻辑解释如下:

“如果特定字段为空,则返回元组,如果不为空,则检查查询的‘where’子句。”

我试着这样写查询,但实际上它不起作用。

String query ="FROM Audit t WHERE (t.emp IS NULL OR t.emp.name LIKE '%')";
listaServer = entityManager.createQuery(query).getResultList();

这是审计表

| ID | EMP    | STATE  |
***********************
|  1 | 150    | Active |
|  2 | (null) | Active |

这是 Emp 表

| ID | Name  |
**************
|150 | Tom   |
|151 | John  |

当我运行查询时,它只返回审计表的第一个元组。我该如何解决?

【问题讨论】:

    标签: java hibernate hql entitymanager


    【解决方案1】:

    我认为您没有所需的 HQL。我认为当实体之间存在关联时,您将需要内部连接。所以我会建议下面的查询

    select a from Audit a join a.emp e where e is not null  OR emp.name LIKE '%'
    

    应该是这样的

    String query ="select a from Audit a join a.emp e where e is not null  OR emp.name LIKE '%'";
    listaServer = entityManager.createQuery(query).getResultList();
    

    【讨论】:

    • 我应该使用左外连接来返回带有空字段的元组,而不是使用带有“where”子句的内连接来检查非空字段。如何在hibernate中进行左连接而不遇到以下异常? ORA-25156: 旧式外连接 (+) 不能与 ANSI 连接一起使用
    【解决方案2】:

    在我看来,是因为这个表达式:t.emp.name LIKE '%' 为了评估这个表达式,hibernate 将生成一个内部连接。 您应该尝试在表之间定义左外连接,并在该范围内运行选择。 像这样的:

    SELECT t from Audit t LEFT JOIN t.emps e WHERE (t.emp IS NULL OR e.name LIKE '%')
    

    【讨论】:

    • 我按照你的建议尝试过,但我有这个例外:ORA-25156: old style outer join (+) cannot be used with ANSI joins
    • 在 JOIN 中使用 ON 代替 WHERE,不推荐使用 WHERE
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2021-02-23
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多