I need some advice with implementing spring JPA query. My query is complex, because of the input length.
As input I've:
- 15 condition - check equality if not null;
- 2 condition - check between if not null
- Additionally, the output must be pageable.
I know that this can be solved by using standard PagingAndSortingRepository like:
Page<A> findAllByParam1AndParam2AndParam3Between...(@Nullable String param1, @Nullable String param2, @Nullable Integer param3,...)
but looking on how long my input is this solution looks unclear and I don't think that method with so many parameters is a good solution. I was also thinking about findAll
by Example, but this is supporting equality, not the between condition.
Any other options?
The only way to go is by building a custom query with CriteriaBuilder?
Derived queries, i.e. those deriving the actual query from the method name, are the wrong tool for such long or complex queries because the resulting name becomes unusable.
Alternatives that you should consider are
using a fixed query provided in a
@Query
annotation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-queryusing a named query where you provide the query on the entity: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.named-queries
using a specification where you dynamically assemble the where clause: https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/