How to implement long/complex query with spring-data-jpa 2.1
Solution 1
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/
Solution 2
You have below options to do that. 1) use hql , for that it is mandatory to have all the tables mapped as jpa entities 2) is to use native queries, the downside here is that it affects the portability of the application, but if u r sure that ur application is not going to migrate on any other database then u can use this 3) is to use criteriabuilder
Edit-> Found our that @Query can be used for both SQL and JPQL to execute .
Please follow below link for more information
https://www.baeldung.com/spring-data-jpa-query
Usage of Query in some spring developer certification books also.
Hope that helps
Paweł S
Updated on July 19, 2022Comments
-
Paweł S almost 2 years
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?