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

How to create a temporary column + when + order by with Criteria Builder

这是我试图用 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 中按此临时列排序?

谢谢

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

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();