Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL Equivalent of SQL Contains

Tags:

sql

contains

hql

I'm trying to write an HQL query to select objects which contain an object in a child collection.

Example:

Contest Object

ContestID  
ContestName  
RequiredCountries -> one to many collection of Country objects  

Country Object

CountryCode  
CountryName  

The sql equivalent of what i want:

SELECT * FROM CONTEST C  
WHERE C.CONTESTID IN(SELECT CONTESTID FROM CONTEST_COUNTRY CC INNER JOIN COUNTRY CTRY ON   
CC.COUNTRYCODE = CTRY.COUNTRYCODE WHERE COUNTRYCODE='USA')

OR

SELECT * FROM CONTEST C  
WHERE EXISTS(SELECT CONTESTID FROM CONTEST_COUNTRY CC INNER JOIN COUNTRY CTRY ON 
CC.COUNTRYCODE = CTRY.COUNTRYCODE WHERE COUNTRYCODE='USA' AND CC.CONTESTID=C.CONTESTID)  

I have this hql, which works, but seems like not a good solution-

from Contest C  
where (from Country where CountryCode = :CountryCode) =  some elements(C.RequiredCountries) 

I also consider joining with Country, but since I don't have an object class to represent the relationship, I wasn't sure how to join in HQL.

Anyone have any ideas or suggestions? This should be easy.

like image 856
Brian Avatar asked Feb 26 '09 19:02

Brian


People also ask

Is HQL similar to SQL?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.

Why we use HQL instead of SQL?

Unlike SQL, HQL uses classes and properties in lieu of tables and columns. HQL supports polymorphism as well as associations, which in turn allows developers to write queries using less code as compared to SQL.

How do you write or condition in HQL query?

The easiest way is to either create the hql string based on the value (if subServiceId is existent or not) or use the criteria api, thus you will just have to add one extra equals filter in case of subServiceId presence. The question should be changed on how to add dynamic conditions to hql based on variable presence.

Is HQL and JPQL same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.


1 Answers

try this:

from Contest Ct, Country Cr
where Cr.CountryCode = :CountryCode 
    and Cr.Country in elements(Ct.RequiredCountries) 

Related article

like image 51
Maksym Gontar Avatar answered Sep 22 '22 23:09

Maksym Gontar