【问题标题】:Order by a list in JPA criteria query按 JPA 条件查询中的列表排序
【发布时间】:2021-09-12 12:51:24
【问题描述】:

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

【问题讨论】:

    标签: java spring-boot spring-mvc spring-data-jpa criteriaquery


    【解决方案1】:

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

    请看看这是否有帮助。

    【讨论】:

      猜你喜欢
      • 2011-05-10
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多