问题描述
我的用例是按照列表中值的顺序对表中的响应进行排序。按预期工作的 MysqL 查询是:
SELECT
property_uuid,micromarket_uuid,city_uuid,SUM(obligation_booked)
FROM
projects_service_pluto.rent_calculated
WHERE
property_uuid IN ('33','121')
GROUP BY zone_uuid,property_uuid
ORDER BY find_in_set(property_uuid,"33,121");
此处“33”和“121”是示例值。我需要在那里放置一个有序列表。我无法将其转换为 JPA Criteria 查询。到目前为止,我已经到了这个:
Set<String> propertySet = new HashSet<>(propertyUuids);
String paramAsstring = String.join(",",propertySet);
Expression<?> orderColumn = builder.function("FIND_IN_SET",List.class,rentCalculatedRoot.get("propertyUuid"),builder.literal(paramAsstring));
query.orderBy(orderColumn); //Here it gives an error saying expected value is Order
用这个代替:
query.orderBy(builder.asc(orderColumn));
解决了编译时错误,但显然给出了错误的输出。这里的解决方案是什么?
TLDR; 在 JPA 条件查询中有没有办法根据值列表对输出进行排序?
解决方法
我们可以使用 orderBy 方法 CriteriaQuery 根据单列或多列数据对数据进行排序。
CriteriaQuery<Test> criteriaQuery = criteriaBuilder.createQuery(Test.class);
Root<Test> from = criteriaQuery.from(Test.class);
CriteriaQuery<Test> select = criteriaQuery.select(Test);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
请看看这是否有帮助。