2011-12-26 69 views
0

我已經使用Hibernate執行查詢,該查詢使用where子句引用單個表。在休眠狀態下執行復雜查詢

我選擇在SQL下面的查詢:

SELECT URN.ID, 
    URN.USERNAME, 
    (SELECT NAME FROM CITY WHERE ID=URN.CITY_ID 
) AS CITY , 
    (SELECT NAME FROM STATE WHERE ID=URN.STATE_ID) AS STATE, 
    (SELECT NAME FROM COUNTRY WHERE ID = URN.COUNTRY_ID) AS COUNTRY 
FROM USERREGISTRATION_NEW URN 

URN.CITY_ID,URN.STATE_ID,URN.COUNTRY_ID包含數值。

城市,州,國家名稱從相應的表上檢索傳遞數字ID。

那麼,我該如何在Hibernate中編寫這個查詢呢?

此外,我不明白多對一,等教程?

我採取了參考從Vaannila

回答

2

這種查詢可以從字面上翻譯成HQL。只需將表名稱更改爲實體類名稱,並將列名稱更改爲實體屬性名稱,然後您將擁有HQL查詢。

但是這個查詢應該用連接書寫。在SQL中,這將是

select urn.id, urn.username, city.name as city, state.name as state, country.name as country 
from USERREGISTRATION_NEW urn 
inner join city on urn.city_id = city.id 
inner join state on urn.state_id = state.id 
inner join country on urn.country_id = country.id 

而且,使用Hibernate,你將有甕城和市,另一個愨骨灰盒州和甕城和國家之間的另一個之間的多對一關係。然後,HQL是:

select urn.id, urn.userName, cityEntity.name as city, stateEntity.name as state, countryEntity.name as country 
from Urn urn 
inner join urn.city as cityEntity 
inner join urn.state as stateEntity 
inner join urn.country as countryEntity 

或更簡單:

select urn.id, urn.userName, urn.city.name as city urn.state.name as state, urn.country.name as country 
from Urn urn