简体   繁体   中英

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 - eg 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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM