Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Spring repository filtering multiple parameters

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 !

like image 400
BlackBishop Avatar asked Apr 07 '16 19:04

BlackBishop


2 Answers

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

like image 116
franDayz Avatar answered Oct 13 '22 20:10

franDayz


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”

like image 1
Patrick Avatar answered Oct 13 '22 19:10

Patrick