ORDER BY in Criteria API for a computed column name (by alias)

后端 未结 4 945
广开言路
广开言路 2021-01-26 04:15

Having a situation where my java code is symbolic to query -

  SELECT CUSTOMER_ID,
         CUSTOMER_NAME,
         CASE
             WHEN COUNT (DISTINCT CARD_ID         


        
相关标签:
4条回答
  • 2021-01-26 05:06

    It seems this is not possible with the JPA Criteria API and you will have to fallback to using JPQL/HQL instead.

    0 讨论(0)
  • 2021-01-26 05:06

    Using the Criteria API, you need to order by the caseSelect expression. I gave it a try and it works fine with Hibernate 5.4. Which version do you use?

    0 讨论(0)
  • 2021-01-26 05:13

    This is fairly not possible and just feels like a case missed by JPA. Though if using hibernate API it is possible. But, my workaround was -

    1. Created a view which would contain the case expression.
    2. Join the view with my entity (you cannot do a join, but one more query.from(View.class)).
    3. In the where add the ids of View and the entity.

    Now in the order by you could mention the column name by View.column_name.

    0 讨论(0)
  • 2021-01-26 05:15

    I faced a similar situation...

    query.multiselect(root, computedColumn);
    query.orderBy(new Order[]{filterDTO.getSortAsc() ? cb.asc(cb.literal(2)) : cb.desc(cb.literal(2))});
    

    I my case computedColumn is Subquery...I did not manage to make it work by column alias but it seems to work by column index returned in the tupple so I guess in your code it should work by index 1

    query.orderBy(cb.asc(cb.literal(1)));
    
    0 讨论(0)
提交回复
热议问题