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 !
Take a look at this post:
http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-four-jpa-criteria-queries/
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
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”
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With