CASE statement in HQL or Criteria

2020-02-11 04:39发布

问题:

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.

回答1:

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