views:

301

answers:

1

HQL noob here. How do I re-write this HQL query without using the exists clause. In SQL I can just join VisitorProfileField table and Visitor table and add the conditions of the exists using an AND.

But in plain HQL I am not able to get past some syntax violation I guess. Your help is much appreciated.

"select distinct v from Visitor v where v.id not in (select o.id from Operator o) " +
      " and exists (select vpf from VisitorProfileField vpf " +
      " where vpf.visitor = v and vpf.profileField.name = :subscription_field " +
      " and vpf.numberVal = :type and vpf.stringVal = :manual) "
+1  A: 

I'm not sure whether I get the meaning of your query, but I guess something like:

select distinct vpf.visitor 
from VisitorProfileField vpf 
where vpf.profileField.name = :subscription_field 
      and vpf.numberVal = :type and vpf.stringVal = :manual
      and vpf.visitor.id not in (select o.id from Operator o)
Fried Hoeben
The meaning goes something like this: select from the visitor list, those folks who are not operators, and who have subscribed to a mailing list. The exists clause helps with finding this last part. In your solution, I don't see the Visitor table being used at all. The original query wants people out of the visitor table who satisfy some condition in VisitorProfileField table.
Senthil
I assumed vpf.visitor gave me visitors. In HQL you don't need to mention all entities (i.e. tables in SQL) explicitly to be able to use them, you can just navigate over relationships. So when I have 'select distinct vpf.visitor' I will get all Visitors reachable via VisitorProfileField that satisfy the clauses.
Fried Hoeben
Are operators a subclass of Visitor? Otherwise the 'not in' seems dangerous. In HQL you can also query on the (sub)class of an object. So if Operator is a subclass of visitor you could actually write 'vpf.visitor.class != Operator'
Fried Hoeben
Fried, thanks much. I guess I was too noob last week when I saw this solution that it did not make any sense to me. Now I have read up a bit and this solution seems perfect. I am still figuring your comment about operator though.
Senthil