Skip to content
Advertisement

How to use SUM(CASE WHEN….) in JPQL Hibernate?

I have the following query:

Query qQuery = entityManager.createQuery("select " +
                "    sum((case when mt.prop1 = true then 1 else 0 end)), " +
                "    sum((case when mt.prop2 = true then 1 else 0 end)), " +
                "    sum((case when mt.prop3 = false then 1 else 0 end)), " +
                "    sum((case when mt.prop3 = true then 1 else 0 end)) " +
                "from MyTable mt " +
                "where mt.id = :myId ");

However, this throws a syntax error on the query when I put a case statement inside an aggregate.

I can get SUM to work fine alone, and case statements to work fine alone. I’m wondering whether JPQL can support cases in aggregates or if I’m forced to use a native query.

Advertisement

Answer

Ugh….. false alarm. IntelliJ is just stupid. I just ran the query and it’s fine. IntelliJ still shows the error but it works.

To anyone who comes across this issue…. just run it before you jump to conclusions, even with the error prompt by IntelliJ or other IDE. Sometimes the IDE is just wrong.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement