如何使用Criteria Builder创建一个临时列+ when + order

时间:2018-12-31 09:23:38

标签: sql-order-by hibernate-criteria temp-tables

这是我要在jpa中转换的sql语句:

  select 
        id,
        act_invalidation_id, 
        last_modification_date,
        title,
        case when act_invalidation_id is null then 1 else 0 end as test
    from act order by test, last_modification_date desc

实际翻译

Root<Act> act = query.from(Act.class);

builder.selectCase()
                .when(builder.isNull(actRoot.get("actInvalidation")), 1)
                .otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);

Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);

query.select(act).orderBy(byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();

我尝试创建一个Integer类型的临时列(名为test),并按此列排序,然后按lastmodificationdate排序。新列的内容由actInvalidation字段的值确定。

简而言之:如何创建一个具有整数值的临时列,然后在jpa中按此临时列排序?

谢谢

1 个答案:

答案 0 :(得分:1)

我没有对此进行测试,但它应该像这样工作:

Root<Act> act = query.from(Act.class);

Expression<?> test = builder.selectCase()
                .when(builder.isNull(actRoot.get("actInvalidation")), 1)
                .otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);

Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);

Order byTest = builder.asc(test);

query.select(act).orderBy(byTest, byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();