Problem does not have direct connection to CASE
expression, in general result variables (sortProperty in this case) cannot be used in WHERE
clause. That's why also following is invalid JPQL:
SELECT u.firstName AS someVar FROM User u WHERE someVar = 'blaa'
Criteria API does not help here. Similar limitation exists also in SQL:
SELECT u.first_name as someAlias
FROM users u
-- someAlias is not known here:
WHERE someAlias = 'blaa'
Whole condition should be pushed to WHERE clause.