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;
这是我的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);
这不起作用返回结果只按字符串优先级排序。选择案例不适用于条件构建查询。
答案 0 :(得分:3)
您选择行cb.desc(root.get("priority"));
原始的“piority”。小心,在你的第一个例子中,你使用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);
答案 1 :(得分:0)
我们也可以使用javax.persistence.criteria.CriteriaBuilder.SimpleCase
// ArrayList<T> order - Define Custom order ArrayList // {"HIGH", "MEDIUM", "LOW", "NOT_ASSIGNED"}
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<TableTest> query = cb.createQuery(TableTest.class);
Root<TableTest> root = query.from(TableTest.class);
query.select(root);
Path<String> priority = root.get("priority");
SimpleCase<String, Integer> orderCase = builder.selectCase(priority);
int i;
for (i = 0; i < order.size(); i++) {
orderCase = orderCase.when(order.get(i),i); // .when("HIGH", 0);
}
query.orderBy(cb.asc(orderCase.otherwise(i)));
entityManager.createQuery(query);
我们可以使用 CriteriaBuilder.SimpleCase 而不是使用 cb.selectCase().when(#)。因为我们可以很容易地循环它。