Spring 数据存储库:findBySomething***In*** 和结果顺序 [英] Spring data repository: findBySomething***In*** and result order

查看:14
本文介绍了Spring 数据存储库:findBySomething***In*** 和结果顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to make those functions getting the results ordered like in the order of the list (or collection) given to the function for the in lookup?

一个spring数据仓库接口函数的简单例子:

Simple example of a spring data repository interface function:

public void ListfindByColorIn(List colors)

现在我创建了一个字符串列表,顺序是green"、blue"、cyan"并调用这个函数.

Now im creating a string list with the order "green", "blue", "cyan" and calling this function.

假设所有这三种颜色都有一个独特的匹配:

Assuming there is a unique match of all these three colors:

如何让函数按照给定列表中的给定属性顺序返回结果?在这个例子中:

how can i make the function returning the results by the given order of property in the given list? In this example:

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

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

Not sure whats the default order in this case but im assuming the id...

推荐答案

spring data 有两个带有 api 的变体如何使用基于属性的标准顺序.

spring data has two variants with api how you can use standard order based on property.

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)

如果你想对 case 使用自定义顺序,排序顺序:color="green" , color="blue", color="青色"

if you want to use custom order for case , sort order : color="green" , color="blue", color="cyan"

您需要使用带有基于您的排序逻辑的自定义排序实现的变体 2.

you need use variant 2 with custom Sort implementation based on your sort logic.

如果结果集很小,您也可以获得未排序的结果并在服务器端对其进行排序.spring 数据可能会返回流,因此您可以执行以下操作:

Also you can get not sorted result and sort it in server side if you have small result set . spring data might return stream , so you can do something like :

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

这篇关于Spring 数据存储库:findBySomething***In*** 和结果顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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