Java Spring Data 动态查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23017419/
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-13 20:02:39  来源:igfitidea点击:

Spring Data dynamic query

javaspringspring-datadynamicquery

提问by Pablo Fallas

I'm trying to set up a dynamic query using spring data, basically I have an array with a bunch of characteristics and I need to assemble the query based on those characteristics, pretty much something like "WHERE characteristic = A AND characteristic = B AND characteristic = C" but the amount of characteristics may vary.

我正在尝试使用 spring 数据设置动态查询,基本上我有一个具有一堆特征的数组,我需要根据这些特征组合查询,几乎类似于“WHERE特性 = A AND 特性 = B AND特征 = C”,但特征的数量可能会有所不同。

I noticed that I can use the @Query annotation but is it possible to make the result of the @Query pageable ?

我注意到我可以使用 @Query 注释,但是否可以使 @Query 的结果可分页?

Is there any other way to accomplish this?

有没有其他方法可以做到这一点?

Page<Recipe> findDistinctByNameContainingAndOrganizationAndCharacteristicsInOrIngredientsContainingAndOrganizationAndCharacteristicsInOrDescriptionContainingAndOrganizationAndCharacteristicsInAllIgnoreCase(
        String name, Organization organization1, List<Characteristic> characteristic1,
        String ingredients, Organization organization2, List<Characteristic> characteristic2,
        String description, Organization organization3, List<Characteristic> characteristic3,
        Pageable pageable);

采纳答案by gipinani

Yes. @Querysupports pageable.. and yes there's another way to accomplish this.

是的。@Query支持可分页.. 是的,还有另一种方法可以做到这一点。

You could take a look at building query with criteria, that allow you add AND / OR where conditions dynamically. I actually use querydsl to facilitate my development.

您可以查看使用条件构建查询,该条件允许您动态添加 AND / OR where 条件。我实际上使用 querydsl 来促进我的开发。

In this post you can find a good explanation of both: http://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

在这篇文章中,您可以找到对两者的很好解释:http: //spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

Altough it could be seem more complex at beginning, the use of this feature will make your code more consistent with increasing complexity

尽管一开始可能看起来更复杂,但使用此功能将使您的代码与日益增加的复杂性更加一致

回答by Pahari Chora

Use Spring Data JPA Querydsl. Read it here

使用 Spring Data JPA Querydsl。在这里阅读