在mysql和condition中使用java predicate

laawzig2  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(395)

我有以下几点 java predicate 从我的 MYSQL 数据库:

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

我想做的是更改上面的代码,以便结果列表必须匹配两个 predicate -例如,必须是 job - "doctor" AND age - 45 我已经尝试组合如下 predicate ,但这总是只返回job predicate :

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

我怎么能这么做?

83qze16e

83qze16e1#

尝试以下操作:

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

相关问题