首页 > 解决方案 > 按 JPA 条件查询中的列表排序

问题描述

我的用例是根据列表中值的顺序对表中的响应进行排序。对按预期工作的 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 , city_uuid , micromarket_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 标准查询中有没有一种方法可以根据值列表对输出进行排序?

标签: javaspring-bootspring-mvcspring-data-jpacriteriaquery

解决方案


我们可以使用 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")));

请看看这是否有帮助。


推荐阅读