简体   繁体   中英

How to Retrieve records from multiple tables using HQL INNERJOIN

I have 3 tables named Class,Person and PersonTalent.

1.Person had Person ID and Name.

2.Class has list of Persons and each person has id as mentioned above.

3.PersonTalent has person Id and Person Talent Name.

Now i want to retrieve the list of records from Class based on the Person Talent Name. How can i achieve that in HQL INNER JOIN.

I have tried like this:

SELECT DISTINCT C FROM Class C, PersonTalent PT
        INNER JOIN C.persons P
        WHERE P.personId = PT.personId AND (PT.personId=1 AND PT.personTalentName='HQL')

With the above code i am getting all Class Objects which matches personId but i need list of class objects which matches both person Id and Person Talent name.

Please help me in achieving this.

Regards, Rajasekhar

select distinct c.* 
from Class c 
inner join person_talent pt on c.person_id=pt.person_id
WHERE PT.personId=1 AND PT.personTalentName='HQL'

IMHO, I define a Class entity without mapping collection with DB.

After that, I'd write first in this way:

SELECT C FROM Class C
WHERE EXISTS(
    SELECT 'X' FROM Person P, Persontalent PT
    WHERE P.fkClass = C.id
    AND P.personId = PT.personId
    AND PT.personId = 1 
    AND PT.personTalentName = 'HQL'
)

After this first query:

I'd write a second query:

SELECT P
FROM Person P, PersonTalent PT
WHERE P.fkClass in (RESULT OF FIRST QUERY)
AND P.personId = PT.personId
AND PT.personId = 1 
AND PT.personTalentName = 'HQL'

After this, I'd write a method to link result of first query (list of Class) with result of second query (list of Person to link to your specific class instance).

PS I suppose you have a property in your Person entity to link with Class entity (I've named fkClass but you know the exact name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM