如何保留“in”中提供的订单Spring Data JPA或Hibernate中的子句 [英] How to keep order provided in "in" clause in Spring Data JPA or Hibernate

查看:235
本文介绍了如何保留“in”中提供的订单Spring Data JPA或Hibernate中的子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



查询:

  @Query(value =select i from ItemEntity i where i.secondaryId in:ids)
List< ItemEntity> itemsIn(@Param(ids)List id,Pageable可分页);

我需要以与 List< UUID> ids ,是否有可能实现这个没有普通的sql,但只有在 Spring Data 和/或 Hibernate

解决方案

您也可以通过JPA来做到这一点,但您必须创建一个以逗号分隔的列表ids按你想要的顺序。在您的情况下,您可以保持相同的顺序。

  @Query(value =从ItemEntity中选择我i where i.secondaryId in: ids 
order by FIND_IN_SET(i.secondaryId,:idStr))
List< ItemEntity> itemsIn(@Param(ids)List< UUID> id,@Param(idStr)String idStr);

要创建逗号分隔列表,您可以使用java 8 stream:

  ids.stream()。map(Object :: toString).collect(Collectors.joining(,)); b 



$ b示例: code> SELECT id FROM User WHERE id in(2,3,1)
ORDER BY FIND_IN_SET(id,2,3,1);

结果:

  + ---- + 
| id |
+ ---- +
| 2 |
| 3 |
| 1 |
+ ---- +


I have a pretty simple query which retrieves values base on "in" clause. List that comes as "in" argument is appropriately sorted.

Query :

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

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.

解决方案

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);

To create comma separated list you can java 8 stream:

ids.stream().map(Object::toString).collect(Collectors.joining(","));

Example:

SELECT id FROM User WHERE id in (2,3,1) 
ORDER BY FIND_IN_SET(id,"2,3,1");

Result:

+----+
| id |
+----+
|  2 |
|  3 |
|  1 |
+----+

这篇关于如何保留“in”中提供的订单Spring Data JPA或Hibernate中的子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆