1 Reply Latest reply on Mar 6, 2011 2:51 AM by Nicklas Karlsson

    Using CriteriaQuery

    Sam W Expert

      Hello,

       

      I want to convert the follow findBy function

       

      Product.java:

      @NamedQuery(name = "Product.findBySalePriceRange", query = "SELECT p FROM Product p WHERE p.sale_price >= :lowEnd AND p.sale_price <= :highEnd order by p.salePrice asc"),

      ...

       

      ProductFacade.java:

      public List<Product> paginatedFindBySalePriceRange(double low, double high, int startPosition, int pageSize) {

              Query q = em.createNamedQuery("Product.findBySalePriceRange");

              q.setParameter("lowEnd", low);

              q.setParameter("highEnd", high);

              q.setFirstResult(startPosition);

              q.setMaxResults(pageSize);

              try {

                return (List<Product>) q.getResultList();

              } catch (NoResultException e) {

                return null;

              }

          }

       

      into the following implementation using CriteriaQuery:


      public List<T> paginatedFindBySalePriceRange(....) {

              javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();

              cq.select(cq.from(entityClass));

              return getEntityManager().createQuery(cq).getResultList();

          }

       

       

      Dose anyone know how to do that?

       

      Any tutorial / wiki links and suggestion would be very appreciated.

       

      Thanks

      Sam