本文介绍了Spring数据存储库:findBySomething *** 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 List<Entity> findByColorIn(List<String> colors)

现在,我将按绿色",蓝色",青色"的顺序创建一个字符串列表,并调用此函数.

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数据具有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 ="cyan"

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

您需要根据您的排序逻辑将变式2与自定义Sort实现结合使用.

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

此外,如果结果集较小,您将无法获得排序结果,而无法在服务器端对其进行排序. spring数据可能会返回stream,因此您可以执行以下操作:

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 ***和结果顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:24