AND operators and OR

Asked

Viewed 140 times

1

I recently started using the Criteria API because I need to make queries that would be very complex with HQL.

How I use the operators AND and OR in queries with Criteria API?

  • 1

    Welcome to Stack Overflow, Roger! Please visit Help center to better understand how the site works, and do the tour! (Is worth a medal...)

  • 1

    What you are looking for can be found here: http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html, in section Expression Methods in the Criteriabuilder Interface

2 answers

1

This would be the example of syntax you seek?

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.where(cb.equal(pet.get(Pet_.name), "Fido")
    .and(cb.equal(pet.get(Pet_.color), "brown")));

0

CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root employee = criteriaQuery.from(Employee.class);
criteriaQuery.where(criteriaBuilder.and(
                    criteriaBuilder.greaterThan(employee.get("salary"), 100000),
                    criteriaBuilder.lessThan(employee.get("salary"), 200000)));
Query query = entityManager.createQuery(criteriaQuery);
List<Employee> result = query.getResultList();

This query returns employees with salaries between 100000 and 200000. Basically the operators AND and OR comes first and within them, separated by commas, comes the conditions.

AND(condicao1,condicao2,condicao3...)

You can also put one inside the other:

AND(OR(condica1,condica2),condica3)

Following reference: https://en.wikibooks.org/wiki/Java_Persistence/Criteria#Where

Browser other questions tagged

You are not signed in. Login or sign up in order to post.