Question

What is the difference between:

  • criteriaBuilder.in(predicate);
  • criteriaQuery.where(predicate);

This seems to give the same results. Am I missing something? Should we choose the builder above the query?

Complete example:

List<String> names = new ArrayList<String>();
names.add("John");
names.add("Emma");

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<PersonEntity> criteriaQuery = criteriaBuilder.createQuery(PersonEntity.class);
Root<PersonEntity> root = criteriaQuery.from(PersonEntity.class);

Predicate predicate = root.get(PersonEntity_.name).in(names);
criteriaBuilder.in(predicate);
// or alternative: criteriaQuery.where(predicate);

List<PersonEntity> list = entityManager.createQuery(cq).getResultList();
Was it helpful?

Solution

criteriaBuilder.in(predicate) creates a new predicate. You should file a bug with your provider if it is adding the predicate to the query, as this will not be portable. According to the specification it creates a new predicate, just as root.get(PersonEntity_.name).in(names) does. The query should only use the predicate if it gets added to it such as by calling criteriaQuery.where(predicate).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top