在 MYSQL AND 条件中使用 Java 谓词
Using Java Predicates in MYSQL AND condition
我有以下基于 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();
我想做的是更改上面的代码,以便结果列表必须匹配 both 谓词 - 例如必须是 job - "doctor" AND age - 45
我试过像下面这样组合谓词,但这总是 returns 工作谓词:
selectQuery = selectQuery.where(jobPredicate).where(agePredicate);
我该怎么做?
试试这样的东西:
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();
我有以下基于 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();
我想做的是更改上面的代码,以便结果列表必须匹配 both 谓词 - 例如必须是 job - "doctor" AND age - 45
我试过像下面这样组合谓词,但这总是 returns 工作谓词:
selectQuery = selectQuery.where(jobPredicate).where(agePredicate);
我该怎么做?
试试这样的东西:
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();