Spring Data dynamic query
Asked Answered
P

2

11

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.

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

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);
Prostate answered 11/4, 2014 at 16:2 Comment(3)
Yes @Query supports PageableCalefactory
Try use QueryDSL. For example in this case you can send any predicate for you repository or service. querydsl.comFoxy
For method declarations like these I'd definitely look into other options like @Query and Querydsl. This method is effectively unusable due to its long name and parameter list.Hak
K
9

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

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.

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/

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

Koerlin answered 11/4, 2014 at 17:27 Comment(0)
C
0

Use Spring Data JPA Querydsl. Read it here

Cubbyhole answered 15/3, 2019 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.