Search code examples
javahibernatecriteria

Syntax where clause in consultation with criteria


I need to put a where clause in my query, but I'm not hitting the correct syntax.

       /*
        * Support listing and POSTing back Origem entities (e.g. from inside an
        * HtmlSelectOneMenu)
        */

         public List<Origem> getAll()
   {

      CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
        CriteriaQuery<Origem> criteria = cb.createQuery(Origem.class);
        Root<Origem> root = criteria.from(Origem.class);
        return this.entityManager.createQuery(
                criteria.select(root).where())
                .getResultList();
   }

In my where clause want to bring all "origem" with id equal to the logged in user. Something like this:

Ex: select * from origin where origem.id = loginBean.origem.getId


Solution

  • Simply use criteria.add(Restrictions.eq()) to your criteria and I think if the id is unique you need to use .uniqueResult() to get the wanted result from your criteria, your code should be like this:

    CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    Criteria cr = cb.createCriteria(Origem.class);
    // add the restriction here
    cr.add(Restrictions.eq("id", loginBean.origem.getId));
    Origem root = (Origem) cr.uniqueResult();