spring-data - Spring数据存储库: findBySomething***In*** and result order

标签 spring-data spring-data-jpa jpql

有什么方法可以让这些函数按照提供给 in 查找函数的列表(或集合)的顺序排序结果吗?

Spring数据存储库接口(interface)函数的简单示例:

public void List<Entity> findByColorIn(List<String> colors)

现在我创建一个顺序为“green”、“blue”、“cyan”的字符串列表并调用此函数。

假设所有这三种颜色都有唯一的匹配:

如何使函数按给定列表中属性的给定顺序返回结果?在此示例中:

Entity[id=32, color="green"]
Entity[id=11, color="blue"]
Entity[id=22, color="cyan"]

不确定这种情况下的默认顺序是什么,但我假设 id...

最佳答案

spring data 有两种 API 变体,如何使用基于属性的标准顺序。

1 个变体:

public void List<Entity> findByColorInOrderByColorDesc(List<String> colors)
public void List<Entity> findByColorInOrderByColorAsc(List<String> colors)

2个变体

Sort sort= new Sort(Sort.Direction.ASC/DESC,"color");
public void List<Entity> findByColorIn(List<String> colors , Sort sort)

如果您想对案例使用自定义顺序,请排序顺序: 颜色=“绿色”,颜色=“蓝色”,颜色=“青色”

您需要根据您的排序逻辑使用带有自定义排序实现的变体 2。

如果结果集较小,您还可以获得未排序的结果并在服务器端对其进行排序。 spring data 可能会返回stream,所以你可以这样做:

findByColorIn(colors).stream().sorted(comparator....).collect(Collectors.toList());

关于spring-data - Spring数据存储库: findBySomething***In*** and result order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45005569/

相关文章:

mongodb - 将 $strLenCP 与 Spring Data MongoDB 结合使用

java - 连接到两个数据库时出现 LazyInitializationException

Spring Data Rest 同一对象的不同数据取决于 uri/files <-> files/1

java - 在 spring jpa 中调用返回没有实体的引用光标的函数

jpa - 用于从 select row_number() over() 中选择的 JPQL

java - 如何使用 Spring JPA 检索某个记录器之前和之后的记录?

mongodb - 如何在 mongodb 的 spring-data 中映射枚举集合

java - 元数据异常 : The type "*.CustomerEntity" has not been enhanced - whentrying to create row with Spring-JPA and OpenJPA

java - 为docker和应用程序设置不同的配置文件是JDBC连接

mysql - JPA 在查询中添加秒数