Search code examples
javamysqlarraylistpredicatecriteriaquery

Using Java Predicates in MYSQL AND condition


I have the following java predicate based code that gets a result list from my MYSQL DB:

Root<Person> from = query.from(Person.class);
CriteriaQuery<Person> selectQuery = query.select(from);
List<Person> searchResults = new ArrayList<>();

Predicate jobPredicate = createPersonJobPredicate();
Predicate agePredicate = createPersonAgePredicate(); //currently not used

selectQuery = selectQuery.where(jobPredicate);
searchResults =entityManager.createQuery(selectQuery).setFirstResult(searchRequest.getIndex()).setMaxResults(searchRequest.getSize()).getResultList();

What I want to do is change the above code so that the result list has to match both predicates - e.g. must be job - "doctor" AND age - 45

I have tried combining the predicates as such below, but this always only returns the job predicate:

selectQuery = selectQuery.where(jobPredicate).where(agePredicate);

How can I do so?


Solution

  • Try something like:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
    Root<Person> personRoot = criteriaQuery.from(Person.class);
    
    Predicate jobPredicate = criteriaBuilder.equal(personRoot.get("job"), "doctor");
    Predicate agePredicate = criteriaBuilder.greaterThan(personRoot.get("age"), 45);
    
    Predicate combinedPredicate = criteriaBuilder.and(jobPredicate, agePredicate);
    criteriaQuery.where(combinedPredicate);
    List<Person> searchResults = 
       entityManager.createQuery(criteriaQuery).getResultList();