2016-02-10 36 views
2

爲什麼這個HQL語句就像一個內部連接?爲什麼這個hql語句就像一個內部連接?

select 
    user.id, 
    user.allocationVersion, 
    user.tx.statusId, 
    user.userId, 
    user.nameFirst, 
    user.nameLast, 
    user.email1, 
    user.statusId, 
    user.tx.name, 
    user.note1, 
    user.note2 
from 
    module.bb.jpa.User as user 
where user.clientId = :clientId 
    order by user.id DESC 

其在用戶類引用的TX類可以是null。爲什麼我會得到一個結果,就好像我做了一個inner join?我只是得到User s與TX,但我想要所有這些。

+0

我們期待更多的解釋和輸出錯誤:) – Musaddique

+0

沒有錯誤。用戶可以有TX,但如果用戶沒有,他不會出現在結果列表中。我希望所有的用戶都能出現,因爲我沒有明確地在TX表上進行內部連接。 – user489872

回答

2

因爲您在用戶中引用了tx.name。如果你在Java中訪問它,但是在HQL中獲取這個列的值,Hibernate會隱式地加入,所以它不應該工作。要獲得所有值,你應該明確地做,幷包含外部連接選項。

-2

我相信你缺少的,其中空部分,它會像右連接

where user.clientId = :clientId or user.clientId IS NULL 
+0

clientId始終設置爲 – user489872

+0

此答案缺少重點。問題不是'clientId',而是隱式連接中使用的'tx'引用 – Vogel612

3

關於這個HQL reference會談在第14.4:

HQL支持兩種形式的協會加入:隱含明確。

上一節中顯示的查詢全部使用顯式形式 ,即在from子句中明確使用了join關鍵字。 這是推薦的形式。

隱式表單不使用join關鍵字。相反, 關聯使用點符號「取消引用」。隱式連接可以在任何HQL子句中出現。 隱式連接導致SQL語句中的內部連接 。

from Cat as cat where cat.mate.name like '%s%' 

[由我突出。

你的HQL基本上等同於爲:

select 
    user.id, 
    user.allocationVersion, 
    user.tx.statusId, 
    user.userId, 
    user.nameFirst, 
    user.nameLast, 
    user.email1, 
    user.statusId, 
    user.tx.name, 
    user.note1, 
    user.note2 
from 
    module.bb.jpa.User as user 
    join module.bb.jpa.Tx as tx -- This is an abbreviated inner join 
where user.clientId = :clientId 
    order by user.id DESC 

要「正確」的這種行爲,你將不得不顯式地指定短left outer joinleft join