在jpa中按顺序选择大小写

MMT*_*MMT 2 java mysql hibernate jpa

SELECT * FROM orderTable order by 
CASE priority when 'CRITICAL' THEN 1 
   when 'HIGH' then 2 
   when 'MEDIUM' then 3 
   when 'LOW' then 4 
   when 'NOT_ASSIGNED' then 5 
end ASC ,
CreatedAt ASC;
Run Code Online (Sandbox Code Playgroud)

这是我的mysql查询及其工作方式。数据库列priority是字符串类型,并且该字符串具有以下优先级

我想要用jpa语言之类的语言

CriteriaBuilder cb = em.getCriteriaBuilder();       
CriteriaQuery<T> cq = cb.createQuery(entityClass);
Root<T> root = cq.from(entityClass);
cb.selectCase().when(cb.equal(root.get("priority"), "CRITICAL"), 1)
    .when(cb.equal(root.get("priority"), "HIGH"), 2)
    .when(cb.equal(root.get("priority"), "MEDIUM"), 3)
    .when(cb.equal(root.get("priority"), "LOW"), 4)
    .when(cb.equal(root.get("priority"), "NOT_ASSIGNED"), 5).;
Order temp2 = cb.desc(root.get("priority"));
cq = cq.orderBy(temp2);
Run Code Online (Sandbox Code Playgroud)

这是行不通的,它只按字符串优先级返回结果。选择的情况下不适用于标准构建查询。

jkl*_*lee 6

用该行选择cb.desc(root.get("priority"));原始的“虚假”。注意,在您的第一个示例中,您使用了asc,第二个使用了desc。我还添加了默认情况。

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<TableTest> cq = cb.createQuery(TableTest.class);
    Root<TableTest> root = cq.from(TableTest.class);
    Expression<Object> caseExpression = cb.selectCase()
            .when(cb.equal(root.get("priority"), cb.literal("CRITICAL")), 1)
            .when(cb.equal(root.get("priority"), cb.literal("HIGH")), 2)
            .when(cb.equal(root.get("priority"), cb.literal("MEDIUM")), 3)
            .when(cb.equal(root.get("priority"), cb.literal("LOW")), 4)
            .when(cb.equal(root.get("priority"), cb.literal("NOT_ASSIGNED")), 5)
            .otherwise(6);
    Order temp2 = cb.desc(caseExpression);
    cq = cq.orderBy(temp2);
Run Code Online (Sandbox Code Playgroud)