JPA Spring repository filtering multiple parameters
Solution 1
Take a look at this post:
You can also implement your repositories "the old way", that is, injecting the entityManager into your repo and creating a findByCriteria method that accepts a custom criteria object. Find here the criteria API docs: https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/querycriteria.html
Another alternative to criteria API would be using JPQL, in wich you create a dynamic query string from the same criteria. JPQL reference: http://docs.oracle.com/javaee/6/tutorial/doc/bnbtg.html
Solution 2
A possible solution is to use querydsl
and predicates
.
There is a post which exactly describes some scenarions for building query langauge for a REST API using Spring Data and Querydsl. tutorial
Also here there is a very short description regarding querydsl and predicates (Step 8 Flexible Predicate execution)
He describes this scenario:
Requirement: “As a user, I want to search for customers by first name, last name, email address and any combination of them”
BlackBishop
Updated on June 04, 2022Comments
-
BlackBishop almost 2 years
I am using a Spring repository as follows in order to filter by date range
public interface CustomerRepo extends CrudRepository<Customer, Long> { public List<Customer> findByCreatedBetween(LocalDate start, LocalDate end); }
it is ridiculous simple and is working fine, but now I need to expand my rest service to keep into account other filter criterias, for example sorted o not sorted, o filter by city and by country. When invoking the service, some parameters may be set and others not. Of course I cannot create a method like findByCreatedBetween to keep into account all possible data combinations. What is the best way to handle this scenario ?
Thanks !
-
BlackBishop about 8 yearsthanks for sharing. I cannot see any slide or presentation at that url, what do you mean with "Step 8 Flexible Predicate execution" ?
-
Patrick about 8 years@BlackBishop yeah there are no slides but in code he documented the steps.