Example usage for javax.persistence.criteria CriteriaQuery orderBy

List of usage examples for javax.persistence.criteria CriteriaQuery orderBy

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery orderBy.

Prototype

CriteriaQuery<T> orderBy(List<Order> o);

Source Link

Document

Specify the ordering expressions that are used to order the query results.

Usage

From source file:net.awired.generic.jpa.dao.impl.GenericDaoImpl.java

/**
 * @param length//w w  w  .java  2 s .c  o  m
 *            maxResult
 * @param start
 *            pagination starting point
 * @param search
 *            search string like ' name: toto , dupont' to search for %toto% on name + %dupont% in all properties
 * @param searchProperties
 *            properties to search or all if null
 * @param orders
 *            sorted result by properties
 * @return
 */
public List<ENTITY> findFiltered(Integer length, Integer start, String search, List<String> searchProperties,
        List<Order> orders) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<ENTITY> query = builder.createQuery(entityClass);
    Root<ENTITY> root = query.from(entityClass);

    if (!Strings.isNullOrEmpty(search)) {
        Predicate[] buildFilterPredicates = BuildFilterPredicates(root, search, searchProperties);
        if (buildFilterPredicates.length > 0) {
            query.where(builder.or(buildFilterPredicates));
        }
    }

    if (orders != null) {
        query.orderBy(OrderToOrder.toJpa(builder, root, orders));
    }

    TypedQuery<ENTITY> q = entityManager.createQuery(query);
    if (start != null) {
        q.setFirstResult(start);
    }
    if (length != null) {
        q.setMaxResults(length);
    }
    return findList(q);
}

From source file:org.openlmis.fulfillment.repository.custom.impl.OrderRepositoryImpl.java

private <T> CriteriaQuery<T> addSortProperties(CriteriaQuery<T> query, Root root, Pageable pageable) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    List<javax.persistence.criteria.Order> orders = new ArrayList<>();
    Iterator<Sort.Order> iterator = pageable.getSort().iterator();
    Sort.Order order;/*from   ww w. ja v a2 s.c  om*/

    while (iterator.hasNext()) {
        order = iterator.next();
        String property = order.getProperty();

        Path path = root.get(property);
        if (order.isAscending()) {
            orders.add(builder.asc(path));
        } else {
            orders.add(builder.desc(path));
        }
    }
    return query.orderBy(orders);
}

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public List<TxInstance> itemsDateRange(Date startDate, Date endDate, int[] range) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(TxInstance.class);
    Root<TxInstance> rt = cq.from(TxInstance.class);
    cq.where(cb.and(rt.get(TxInstance_.completed).isNotNull(),
            cb.between(rt.get(TxInstance_.completed), startDate, endDate)));
    cq.orderBy(cb.asc(rt.get(TxInstance_.completed)));
    Query q = em.createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);/*from w  ww.j  a v a 2s .  co  m*/
    return q.getResultList();
}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/**
 * /*from w w w .jav  a2s.  co m*/
 * @param metric
 * @return
 * @throws uQasarException
 */
private List<JiraMetricMeasurement> getMeasurementsByMetricAndDate(String metric, Date date)
        throws uQasarException {
    logger.info("Get measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList();
}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/**
 * /*from  ww w.  j  a v a2 s . c  o  m*/
 * @param metric
 * @param date
 * @return
 * @throws uQasarException
 */
public int countMeasurementsByMetricAndDate(String metric, Date date) throws uQasarException {
    logger.info("Count measurements for metric: " + metric + " and date: " + date);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    Integer res = em.createQuery(query).getResultList().size();
    logger.info("Results' count: " + res);
    return res;
}

From source file:gov.gtas.repository.CaseDispositionRepositoryImpl.java

@Override
public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Case> q = cb.createQuery(Case.class);
    Root<Case> root = q.from(Case.class);
    List<Predicate> predicates = new ArrayList<>();

    TypedQuery<Case> typedQuery = em.createQuery(q);

    // sorting/*  w w w.j av a 2 s. co  m*/
    if (dto.getSort() != null) {
        List<Order> orders = new ArrayList<>();
        for (SortOptionsDto sort : dto.getSort()) {
            Expression<?> e = root.get(sort.getColumn());
            Order order;
            if ("desc".equalsIgnoreCase(sort.getDir())) {
                order = cb.desc(e);
            } else {
                order = cb.asc(e);
            }
            orders.add(order);
        }
        q.orderBy(orders);
    }

    if (dto.getFlightId() != null) {
        predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId()));
    }

    if (dto.getPaxId() != null) {
        predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId()));
    }

    if (dto.getPaxName() != null) {
        String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getLastName() != null) { // map this to full pax name
        String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getStatus() != null) {
        String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase());
        predicates.add(cb.like(root.<String>get("status"), likeString));
    }

    if (dto.getFlightNumber() != null) {
        predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber()));
    }

    if (dto.getRuleCatId() != null) {
        predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId()));
    }

    Predicate etaCondition;
    if (dto.getEtaStart() != null && dto.getEtaEnd() != null) {

        Path<Date> eta = root.<Date>get("flightETADate");
        Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart()));
        Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd()));
        etaCondition = cb.and(startPredicate, endPredicate);
        predicates.add(etaCondition);
    }

    q.select(root).where(predicates.toArray(new Predicate[] {}));
    typedQuery = em.createQuery(q);

    // total count
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {}));
    Long count = em.createQuery(countQuery).getSingleResult();

    // pagination
    int pageNumber = dto.getPageNumber();
    int pageSize = dto.getPageSize();
    int firstResultIndex = (pageNumber - 1) * pageSize;
    typedQuery.setFirstResult(firstResultIndex);
    typedQuery.setMaxResults(dto.getPageSize());

    logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString());
    List<Case> results = typedQuery.getResultList();

    return new ImmutablePair<>(count, results);

}

From source file:eu.uqasar.service.dataadapter.JiraDataService.java

/** 
 * @param metric/*from  www  .  ja va 2  s  .c o  m*/
 * @param project
 * @return
 * @throws uQasarException
 */
public List<JiraMetricMeasurement> getMeasurementsPerProjectByMetricWithLatestDate(Project project,
        String metric) throws uQasarException {
    logger.info("Count measurements for project + " + project.getAbbreviatedName() + " and metric: " + metric
            + "with latest date");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);

    Predicate condition1 = cb.equal(root.get(JiraMetricMeasurement_.jiraMetric), metric);
    Predicate condition2 = cb.equal(root.get(JiraMetricMeasurement_.project), project);

    Predicate condition4 = cb.and(condition1, condition2);
    query.where(condition4);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    List<JiraMetricMeasurement> returnResults = em.createQuery(query).getResultList();

    Date newDate = null;
    for (JiraMetricMeasurement jMM : returnResults) {
        if (newDate == null || jMM.getTimeStamp().compareTo(newDate) > 0) {
            newDate = jMM.getTimeStamp();
        }

    }

    return getMeasurementsByMetricAndDate(metric, newDate);
}

From source file:br.nom.abdon.gastoso.dal.FatosDao.java

private void trataOrdenacao(final FiltroFatos filtro, final Root<Fato> root, final CriteriaBuilder cb,
        final CriteriaQuery<Fato> q) {

    final List<FiltroFatos.ORDEM> ordem = filtro.getOrdem();
    if (ordem != null && !ordem.isEmpty()) {
        List<Order> orders = new LinkedList<>();

        for (FiltroFatos.ORDEM itemOrdenacao : ordem) {
            final Path path;

            switch (itemOrdenacao) {
            case POR_CRIACAO:
                path = root.get("id");
                break;
            case POR_DESCRICAO:
                path = root.get("descricao");
                break;
            case POR_DIA:
            default:
                path = root.get("dia");
                break;
            }/*from w w w  .j  a  va  2 s.c o m*/

            orders.add(cb.asc(path));
        }

        q.orderBy(orders);
    }

}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * /*from  w  w w  .  ja v a2 s. c om*/
 * @param metric
 * @param date
 * @return
 * @throws uQasarException
 */
public int countMeasurementsByMetricAndDate(String metric, Date date) throws uQasarException {
    logger.info("Count measurements for metric: " + metric + "and date: " + date);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    Predicate condition2 = cb.equal(root.get(CubesMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList().size();
}

From source file:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * //from ww w .  j  a  va2 s.  co m
 * @param metric
 * @return
 * @throws uQasarException
 */
private List<CubesMetricMeasurement> getMeasurementsByMetricAndDate(String metric, Date date)
        throws uQasarException {
    logger.info("Get measurements for metric: " + metric);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    Predicate condition = cb.equal(root.get(CubesMetricMeasurement_.cubesMetric), metric);
    Predicate condition2 = cb.equal(root.get(CubesMetricMeasurement_.timeStamp), date);
    Predicate condition3 = cb.and(condition, condition2);
    query.where(condition3);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).getResultList();
}