【问题标题】:How to keep order provided in "in" clause in Spring Data JPA or Hibernate [duplicate]如何保持 Spring Data JPA 或 Hibernate 中“in”子句中提供的顺序 [重复]
【发布时间】:2018-04-12 21:01:08
【问题描述】:

我有一个非常简单的查询,它根据“in”子句检索值。作为“in”参数出现的列表被适当地排序。

查询:

@Query(value = "select i from ItemEntity i where i.secondaryId in :ids")
List<ItemEntity> itemsIn(@Param("ids") List<UUID> ids, Pageable pageable);

我需要以与List&lt;UUID&gt; ids 相同的方式对结果进行排序,是否可以在没有普通 sql 的情况下实现这一点,但只有在 Spring Data 和/或 Hibernate 的帮助下才能实现。

【问题讨论】:

  • 即使使用普通的 SQL,我也看不出你是怎么做到的。您需要通过比较项目实体的 ID 在 ID 列表中的位置来对返回的列表进行排序。

标签: java hibernate spring-data spring-data-jpa jpql


【解决方案1】:

您也可以通过 JPA 执行此操作,但您必须按照您想要的顺序创建一个逗号分隔的 id 列表。在您的情况下,您可以保持相同的顺序。

@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 流:

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 的替代方法:

You can use ,,FIELD'' instead of ,,FIND_IN_SET ''.

您可以在此处找到示例: https://stackoverflow.com/a/65943906/15101302

【讨论】:

  • 这将返回“错误:函数 find_in_set(bigint, character varying) 不存在”,'u' 来自 u.secondaryId?它应该是一个字符串吗?
  • FIND_IN_SET 似乎不是 JPQL 构造(而是 MySQL)。
猜你喜欢
  • 2012-12-17
  • 2021-11-04
  • 2014-01-25
  • 1970-01-01
  • 2011-08-31
  • 2014-09-10
  • 2017-03-15
  • 2018-09-19
  • 2018-06-08
相关资源
最近更新 更多