A simple query for JPA 2 "where" criteria

I am learning the basics of jpa-hibernate.

I have this request for all users:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        cq.select(cq.from(Utente.class));
        return getEntityManager().createQuery(cq).getResultList();

Now I want to filter a logical field named "ghost", where it is true (or false, it depends).

Translated:

SELECT * FROM users WHERE ghost = 0;

Do I need to use cq.where ()? How?

+3
source share
1 answer

Yes you should use cq.where().

Try something like this:

Root<Utente> utente = cq.from(Utente.class);
boolean myCondition = true;    // or false
Predicate predicate = cb.equal(utente.get(Utente_.ghost), myCondition);
cq.where(predicate);

Where I used the class of canonical metamodels Utente_, which should be generated automatically. This avoids errors when entering field names and increases type safety. Otherwise you can use

Predicate predicate = cb.equal(utente.get("ghost"), myCondition);
+7
source

All Articles