Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CASE statement in HQL or Criteria

derived from this question, is it possible to use HQL or Criteria for the following SQL statement:

SELECT 
   e.type, 
   count(e), 
   count(d), 
   count (case when gender = 'male' then 1 else NULL end) AS NumberOfMaleEmployees
from Department d 
JOIN d.employees e
WHERE e.dead = 'maybe' 
GROUP BY e.type

Although google comes up with a few hits that state HQL supports CASE statements, Hibernate 3.6.6 fails with a

QuerySyntaxException: unexpected token: CASE

when I create the query above on an EntityManager instance.

How much of a bad idea is it, to create another query for every e.type to determine the number of males manually, e.g. for every e.type

SELECT 
   count(e), 
from Department d 
JOIN d.employees e
WHERE e.dead = 'maybe', e.type = ugly

Since there could be quite a few types, this is potentially slow. I'd like the database to do the work for me.

like image 692
Clayton Louden Avatar asked Aug 15 '11 17:08

Clayton Louden


1 Answers

Well, it seems, case statements are supported:

http://docs.jboss.org/hibernate/core/3.5/reference/en/html/queryhql.html

They just don't seem to work within count(). An alternative would be using sum(case when... then 1 else 0 end) instead

like image 141
Clayton Louden Avatar answered Sep 24 '22 23:09

Clayton Louden