2012-03-28 77 views
0

我有以下表:排序條件HQL

SN,d和C具有以下鏈接:

SN含有FK到d(D_ID)(多對一),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來排序。因爲在查詢創建時,我們不知道通過的「德公司」進行排序,我已經試過這樣: "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是空?

感謝

回答

1

我想這個問題是,你的表達sn.d.name你強迫休眠聯接表SN和d內部,有效果你就不會取得sn.d是空行,即使SN .cd爲空。 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)

出於調試目的,我建議設置<property name="show_sql">true</property>在你的hibernate.cfg.xml文件。然後你可以檢查你的代碼創建的Hibernate語句有什麼問題,或者檢查我的命題(我沒有測試過,它可能不是100%正確的)。

+0

謝謝你的建議。不幸的是,左外連接和右外連接都給出錯誤:「加入的路徑!」。有任何想法嗎? – AndaP 2012-03-28 18:31:28

+0

好的解決了這個問題之前,對不起。 Next..I得到「java.lang.IllegalArgumentException異常:不能超過一個返回查詢創建TypedQuery」因爲我有希望作爲結果的SN列表的查詢。 – AndaP 2012-03-28 18:50:35

+0

我的不好,只需在查詢的開頭添加:「select sn」。它現在有效!所以,在端查詢看起來像:從SN SN左外「中選擇SN加入sn.dd內連接sn.cc其中(sn.d不爲空或sn.cd不爲空)以便通過聚結(d.name ,cdname)「 – AndaP 2012-03-28 19:07:15