【问题标题】:Order by condition HQL按条件排序 HQL
【发布时间】:2012-03-28 12:49:43
【问题描述】:

我有以下表格:

SN、D 和 C 有以下链接:

SN 包含一个 FK 到 D (d_id) (ManyToOne),SN 包含一个 FK 到 C (c_id)(OneToOne),C 有一个 FK 到 D (d_id, OneToOne)。 D 还包含(在其他列中,一个字符串 number 和一个字符串 name)。

现在,我有一个这样的 HQL 查询:"from SN sn where (sn.d is not null or sn.c.d is not null)"(因此,如果 sn.d 为空,则从 sn.c.d 中获取 d)。不过,这个集合应该可以按 d.number 或 d.name 排序。因为在查询创建时我们不知道按哪个“d”排序,所以我尝试过这样的: "from SN sn where (sn.d is not null or sn.c.d is not null) order by coalesce (sn.d.name, sn.c.d.name)" 但它不起作用,我得到的结果比正常选择少;我也尝试了"order by case when sn.d is not null then sn.d.name else sn.c.d.name",但结果相同。

如果 HQL 中第一列为空,我如何按另一列排序?

谢谢

【问题讨论】:

    标签: sql hibernate sql-order-by hql


    【解决方案1】:

    我猜问题是,使用您的表达式sn.d.name,您强制休眠在内部加入表 SN 和 D,结果您不会获得 sn.d 为空的行,即使 sn.c.d 为空. sn.c.d.name 也一样。

    尝试将 SN 和 D 之间的连接明确定义为外连接,如下所示: from SN sn outer join D d inner join C c where (sn.d is not null or sn.c.d is not null) order by coalesce (d.name, c.d.name)

    出于调试目的,我建议在 hibernate.cfg.xml 文件中设置 <property name="show_sql">true</property>。然后您可以检查从您的代码创建的语句 hibernate 有什么问题或检查我的提议(我没有测试,它可能不是 100% 正确)。

    【讨论】:

    • 感谢您的建议。不幸的是,左外连接和右外连接都给出了错误:“连接的预期路径!”。有什么想法吗?
    • 好的,在抱歉之前解决了这个问题。接下来..我得到“java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return”,因为我有一个查询,它需要一个 SN 列表作为结果。
    • 我的错,只需要在查询的开头添加:“select sn”。现在可以了!!!所以,最后的查询看起来像:“select sn from SN sn left outer join sn.d d inner join sn.c c where (sn.d is not null or sn.c.d is not null) order by coalesce (d.name , c.d.name)"
    猜你喜欢
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多