Java 如何在 Spring Data (JPA) 派生查询中按多个属性排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25380984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:16:41  来源:igfitidea点击:

How to sort by multiple properties in Spring Data (JPA) derived queries?

javaspringjpaspring-dataspring-data-jpa

提问by PDStat

I'm looking at the examples giving on this page (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories) about method naming, is it possible to create a complex chain method name such as

我正在查看此页面上提供的示例(https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories)关于方法命名,是否可以创建一个复杂的链方法名称,例如

findByProgrammeAndDirectorAndProgDateBetweenOrderByProgDateStartTimeAsc

In the example they give, they are only doing an OrderBy on one value. In the example above ProgDateand StartTimewould be two separate values.

在他们给出的示例中,他们只对一个值执行 OrderBy。在上面的示例中,ProgDateandStartTime将是两个单独的值。

采纳答案by Oliver Drotbohm

The trick is to simply delimit the properties you want to sort by using the direction keywords Ascand Desc. So what you probably want in your query method is something like:

诀窍是使用方向关键字Asc和简单地分隔要排序的属性Desc。所以你可能想要在你的查询方法中是这样的:

…OrderByProgDateAscStartTimeAsc

Note, how we conclude the first property definition by Ascand keep going with the next property.

请注意,我们如何通过Asc下一个属性来结束第一个属性定义并继续进行。

Generally speaking, we recommend switching to @Querybased queries, once method names exceed a certain length or complexity. The main reason being that it's awkward for clients to call these very long methods. With @Queryyou rather get the full power of the query language plus a reasonably sized method name that might be of higher level language to express the intent of the query.

一般来说@Query,一旦方法名称超过一定长度或复杂度,我们建议切换到基于查询。主要原因是客户端调用这些很长的方法很尴尬。有了@Query你而得到的查询语言的强大功能加上,可能是更高级的语言来表达的意图查询的合理大小的方法名。

回答by Paulo Fidalgo

Yes it's should be possible:

是的,它应该是可能的:

Try this:

尝试这个:

findByProgrammeAndDirectorAndProgDateBetweenOrderByProgDateStartTimeAsc(String programme, String director, Date progStart, Date progEnd);

I have not tested the code, but according to things I've already done, it should work.

我还没有测试过代码,但根据我已经做过的事情,它应该可以工作。