Ankit
Ankit

Reputation: 433

Perform Complex Queries in Hibernate

I had performed query using Hibernate that refers to single table with where clause.

I am selecting following query in 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 contains numeric values.

City, State, Country name are retrieved from respective table on passing numeric id.

So, how can I write this query in Hibernate?

Also, I don't understand the Many-to-One,etc tutorials?

I had taken Reference from Vaannila

Upvotes: 0

Views: 1283

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

This query can be translated literally to HQL. Just change table names into entity class names, and column names into entity property names, and you'll have your HQL query.

But this query should be written with joins. In SQL, it would be

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

And, using Hibernate, you would have a ManyToOne association between Urn and City, another one betwen Urn and State, and another one between Urn and Country. The HQL would then be:

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

or even simpler:

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

Upvotes: 2

Related Questions