Is there any way to do the following in HQL:
SELECT
case when flag = true then SUM(col1) else SUM(col2)
FROM
myTable
Is there any way to do the following in HQL:
SELECT
case when flag = true then SUM(col1) else SUM(col2)
FROM
myTable
I facing the same problem in HQL then I solved the following query is
See Hibernate-Forum: https://forum.hibernate.org/viewtopic.php?t=942197
Answer from Team (Gavin): case is supported in the where clause, but not in the select clause in HB3.
And seen in JIRA with State "Unresolved".
I guess you can (3.6, 4.3) [inline edit] ...for where-clauses:
Below you can find a working query (hibernate on postgresql) that uses 2 case statements to replace a boolean value with the corresponding textual representation.
We use hibernate HQL query extensively and I think finally there is a hackish way of doing such a thing :
Assuming we originally had a query of
i2.element.id = :someId
Then decided to expand this to be something like this:
((i.element.id = :someId and i2.element.id=:someId) or (i2.element.id = :someId))
But there was an issue where we want it to only lookup for this based on classType so a case statement:
Above will not work you could make an easy version of above work by doing:
But this does not actually do what we need it to do, we want it to do exact above query, so knowing you can assign a variable at the end of a case statement in there where bit of HQL:
I have managed to make the query now work based on case statement, sure it is a lot more long winded but actually does the same as the first instance
Apparently the ability to do this was added in 3.0.4, with the limitation that you cannot use sub-selects in the else clause.