Java Persistence Criteria API - case expressions in orderBy()
<p>I need to order the result of my query by a field if not null otherwise by another field.</p>

<p>This is my code:</p>

<pre><code>Expression condizione=cb.isNotNull(root.get(Attribuzione_.dataprincipale));
Expression principale=root.get(Attribuzione_.dataprincipale);
Expression creato=root.get(Attribuzione_.recordcreato);
Order ord=cb.desc(cb.selectCase()
        .when(condizione, principale)
        .otherwise(creato));
cq=cq.orderBy(ord);
</code></pre>

<p>This code causes an <code>Internal Exception: org.postgresql.util.PSQLException</code>
because the translation in SQL code is not the "order by" I need:</p>

<pre><code>ORDER BY CASE WHEN (t0.dataprincipale IS NOT NULL) THEN (t0.dataprincipale IS NOT NULL) ELSE t0.rec_creato END  DESC
</code></pre>

<p>instead of </p>

<pre><code>ORDER BY CASE WHEN (t0.dataprincipale IS NOT NULL) THEN t0.dataprincipale ELSE t0.rec_creato END  DESC
</code></pre>

<p>But I don't understand where is the fault in my code.</p>

<p>Any suggestion?
Thank you</p>