How to keep order provided in quot;inquot; clause in Spring Data JPA or Hibernate(如何保持“in中提供的订单Spring Data JPA 或 Hibernate 中的子句)
问题描述
我有一个非常简单的查询,它根据in"子句检索值.作为in"参数出现的列表被适当地排序.
I have a pretty simple query which retrieves values base on "in" clause. List that comes as "in" argument is appropriately sorted.
查询:
@Query(value = "select i from ItemEntity i where i.secondaryId in :ids")
List<ItemEntity> itemsIn(@Param("ids") List<UUID> ids, Pageable pageable);
我需要以与 List<UUID> 相同的方式对结果进行排序.ids,是否有可能在没有普通 sql 的情况下实现这一点,但只能在 Spring Data 和/或 Hibernate 的帮助下实现.
I need results to be ordered the same way as List<UUID> ids, is it possible to achieve this without plain sql but only with the help of Spring Data and/or Hibernate.
推荐答案
你也可以通过 JPA 做到这一点,但你必须按照你想要的顺序创建一个逗号分隔的 id 列表.在您的情况下,您可以保持相同的顺序.
You can do that by JPA too but you will have to create a comma separated list of ids in the order you want. In your case you can keep same order.
@Query(value = "select i from ItemEntity i where i.secondaryId in :ids
order by FIND_IN_SET(i.secondaryId, :idStr)")
List<ItemEntity> itemsIn(@Param("ids") List<UUID> ids, @Param("idStr") String idStr);
要创建逗号分隔列表,您可以使用 java 8 流:
To create comma separated list you can java 8 stream:
ids.stream().map(Object::toString).collect(Collectors.joining(","));
例子:
SELECT id FROM User WHERE id in (2,3,1)
ORDER BY FIND_IN_SET(id,"2,3,1");
结果:
+----+
| id |
+----+
| 2 |
| 3 |
| 1 |
+----+
还有一种使用 JPQL 的替代方法:
There is also one alternative using JPQL:
You can use ,,FIELD'' instead of ,,FIND_IN_SET ''.
您可以在此处找到示例:https://stackoverflow.com/a/65943906/15101302
You can find the example here: https://stackoverflow.com/a/65943906/15101302
这篇关于如何保持“in"中提供的订单Spring Data JPA 或 Hibernate 中的子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何保持“in"中提供的订单Spring Data JPA 或 Hibernate 中的子句
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
