我使用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
答案 0 :(得分: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,你会在Urn和City之间建立一个ManyToOne关联,另一个在Urn和State之间,而另一个在Urn和Country之间。那么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