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:fi.vm.sade.organisaatio.dao.impl.OrganisaatioDAOImpl.java

@Override
public List<Organisaatio> findByOidList(List<String> oidList, int maxResults) {
    LOG.debug("findByOidList({}, {})", oidList, maxResults);

    // first drop nulls from oidList
    List<String> oidListFiltered = new ArrayList<>();
    for (String oid : oidList) {
        if (oid != null) {
            oidListFiltered.add(oid);/*from  w  ww .  j a v  a2 s  . c  o m*/
        }
    }

    // perform query
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Organisaatio> query = cb.createQuery(Organisaatio.class);
    Root<Organisaatio> organisaatio = query.from(Organisaatio.class);
    query.orderBy(cb.asc(organisaatio.get("nimihaku")));
    Predicate where = cb.in(organisaatio.get("oid")).value(oidListFiltered);
    query.where(where);
    return getEntityManager().createQuery(query).setMaxResults(maxResults).getResultList();

}

From source file:net.groupbuy.dao.impl.BaseDaoImpl.java

protected Page<T> findPage(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    Assert.notNull(criteriaQuery);//from   w  w w  . java2s .  c  om
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    if (pageable == null) {
        pageable = new Pageable();
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Root<T> root = getRoot(criteriaQuery);
    addRestrictions(criteriaQuery, pageable);
    addOrders(criteriaQuery, pageable);
    if (criteriaQuery.getOrderList().isEmpty()) {
        if (OrderEntity.class.isAssignableFrom(entityClass)) {
            criteriaQuery.orderBy(criteriaBuilder.asc(root.get(OrderEntity.ORDER_PROPERTY_NAME)));
        } else {
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get(OrderEntity.CREATE_DATE_PROPERTY_NAME)));
        }
    }
    long total = count(criteriaQuery, null);
    int totalPages = (int) Math.ceil((double) total / (double) pageable.getPageSize());
    if (totalPages < pageable.getPageNumber()) {
        pageable.setPageNumber(totalPages);
    }
    TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    query.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
    query.setMaxResults(pageable.getPageSize());
    return new Page<T>(query.getResultList(), total, pageable);
}

From source file:de.tudarmstadt.ukp.csniper.webapp.security.dao.AbstractDao.java

/**
 * Finds all entities that have the same type as the given example and all fields are equal to
 * non-null fields in the example.//w w w .  ja v a  2  s .  co  m
 */
protected <TT> CriteriaQuery<TT> queryByExample(TT aExample, String aOrderBy, boolean aAscending) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    @SuppressWarnings("unchecked")
    CriteriaQuery<TT> query = cb.createQuery((Class<TT>) aExample.getClass());
    @SuppressWarnings("unchecked")
    Root<TT> root = query.from((Class<TT>) aExample.getClass());
    query.select(root);

    List<Predicate> predicates = new ArrayList<Predicate>();
    BeanWrapper a = PropertyAccessorFactory.forBeanPropertyAccess(aExample);

    // Iterate over all properties
    for (PropertyDescriptor d : a.getPropertyDescriptors()) {
        Object value = a.getPropertyValue(d.getName());

        // Only consider writeable properties. This filters out e.g. the "class" (getClass())
        // property.
        if (value != null && a.isWritableProperty(d.getName())) {
            predicates.add(cb.equal(root.get(d.getName()), value));
        }
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }

    if (aOrderBy != null) {
        if (aAscending) {
            query.orderBy(cb.asc(root.get(aOrderBy)));
        } else {
            query.orderBy(cb.desc(root.get(aOrderBy)));
        }
    }

    return query;
}

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

/**
 * /*from  w  ww  . j a va  2s.c  o  m*/
 * @param metric
 * @return
 * @throws uQasarException
 */
public List<JiraMetricMeasurement> getMeasurementsPerProjectByMetricWithinPeriod(Project project, String metric,
        String period) throws uQasarException {

    List<JiraMetricMeasurement> measurements = new ArrayList<>();
    if (project != null && metric != null && period != null) {
        logger.info(
                "Count measurements for project + " + project.getAbbreviatedName() + " and metric: " + metric);

        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);

        Date from = getDateForPeriod(period);
        Date to = DateTime.now().toDate();
        Predicate condition3 = cb.between(root.get(JiraMetricMeasurement_.timeStamp), from, to);
        //      System.out.println("from:"+from);
        //      System.out.println("to:"+to);

        Predicate condition4 = cb.and(condition1, condition2, condition3);
        query.where(condition4);
        query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
        measurements = em.createQuery(query).getResultList();
    }

    return measurements;
}

From source file:se.inera.intyg.intygstjanst.persistence.model.dao.impl.CertificateDaoImpl.java

@Override
public List<Certificate> findCertificate(Personnummer civicRegistrationNumber, List<String> types,
        LocalDate fromDate, LocalDate toDate, List<String> careUnits) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Certificate> query = criteriaBuilder.createQuery(Certificate.class);
    Root<Certificate> root = query.from(Certificate.class);

    root.fetch("states", JoinType.LEFT);

    if (civicRegistrationNumber == null) {
        return Collections.emptyList();
    }/*ww w  . j  a va  2  s . c o  m*/

    List<Predicate> predicates = new ArrayList<>();

    // meta data has to match civic registration number
    predicates.add(criteriaBuilder.equal(root.get("civicRegistrationNumber"),
            DaoUtil.formatPnrForPersistence(civicRegistrationNumber)));

    // filter by certificate types
    if (types != null && !types.isEmpty()) {
        predicates.add(criteriaBuilder.lower(root.<String>get("type")).in(toLowerCase(types)));
    }

    // filter by care unit
    if (careUnits != null && !careUnits.isEmpty()) {
        predicates.add(root.<String>get("careUnitId").in(careUnits));
    }

    query.where(predicates.toArray(new Predicate[predicates.size()]));

    // order by signed date
    query.orderBy(criteriaBuilder.asc(root.get("signedDate")));

    List<Certificate> tmpResult = entityManager.createQuery(query).getResultList();
    List<Certificate> result = filterDuplicates(tmpResult);

    // expect a small number, so lets filter in memory
    return new DateFilter(result).filter(fromDate, toDate);
}

From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java

/**
 * {@inheritDoc}//from  w w  w . j  a v a2s .  co m
 */
@Override
public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user,
        final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId,
        final String commandName, final String commandId, final Date minStarted, final Date maxStarted,
        final Date minFinished, final Date maxFinished, @NotNull final Pageable page) {
    log.debug("called");

    final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
    final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    final Root<JobEntity> root = countQuery.from(JobEntity.class);

    final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags,
            clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName,
            commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted,
            minFinished, maxFinished);

    countQuery.select(cb.count(root)).where(whereClause);

    final Long count = this.entityManager.createQuery(countQuery).getSingleResult();

    // Use the count to make sure we even need to make this query
    if (count > 0) {
        final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class);
        contentQuery.from(JobEntity.class);

        contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user),
                root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished),
                root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName));

        contentQuery.where(whereClause);

        final Sort sort = page.getSort();
        final List<Order> orders = new ArrayList<>();
        sort.iterator().forEachRemaining(order -> {
            if (order.isAscending()) {
                orders.add(cb.asc(root.get(order.getProperty())));
            } else {
                orders.add(cb.desc(root.get(order.getProperty())));
            }
        });

        contentQuery.orderBy(orders);

        final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery)
                .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList();

        return new PageImpl<>(results, page, count);
    } else {
        return new PageImpl<>(Lists.newArrayList(), page, count);
    }
}

From source file:com.sapito.db.dao.AbstractDao.java

public List<T> findBySpecificField(String field, Object fieldContent, String predicates,
        LinkedHashMap<String, String> ordering, LinkedList<String> grouping) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    Predicate predicate = null;//  w  w w. j  av  a  2  s . c om

    if (predicates.equals("equal")) {
        predicate = cb.equal(root.get(field), fieldContent);
    } else if (predicates.equals("likelower")) {
        predicate = cb.like(cb.lower(root.<String>get(field)), fieldContent.toString());
    } else if (predicates.equals("like")) {
        predicate = cb.like(root.<String>get(field), "%" + fieldContent.toString() + "%");
    }

    cq.select(root);
    cq.where(predicate);

    if (ordering != null) {
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order;
            if (ordering.get(orderingField).equals("ASC")) {
                order = cb.asc(root.get(orderingField));
            } else {
                order = cb.desc(root.get(orderingField));
            }
            orders.add(order);
        }
        cq.orderBy(orders);
    }

    if (grouping != null) {
        Iterator iterator = grouping.iterator();
        List<Expression> groups = new LinkedList<>();
        while (iterator.hasNext()) {
            groups.add(root.get(iterator.next().toString()));
        }
        cq.groupBy(groups);
    }

    Query query = entityManager.createQuery(cq);
    query.setMaxResults(MAX_RECORDS_RETURNED);

    return query.getResultList();
}

From source file:com.carser.viamais.vo.TransactionFilter.java

public List<Transaction> resultList(final EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Transaction> cq = cb.createQuery(Transaction.class);
    Root<Transaction> transaction = cq.from(Transaction.class);
    cq.where(getPredicates(cb, transaction));
    @SuppressWarnings("rawtypes")
    Path path;/*from w  ww . ja  va 2 s. c  o m*/
    switch (orderBy) {
    case CUSTOMER_NAME:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    case DATE:
        path = transaction.get(Transaction_.transactionDate);
        break;
    case PLATE:
        path = transaction.get(Transaction_.car).get(Car_.licensePlate);
        break;
    case TYPE:
        path = transaction.get(Transaction_.type);
        break;
    case YEAR:
        path = transaction.get(Transaction_.car).get(Car_.yearOfModel);
        break;
    default:
        path = transaction.get(Transaction_.car).get(Car_.model).get(Model_.name);
        break;
    }
    switch (order) {
    case DESC:
        cq.orderBy(cb.desc(path));
        break;
    default:
        cq.orderBy(cb.asc(path));
        break;
    }
    TypedQuery<Transaction> query = em.createQuery(cq);
    query.setFirstResult(offset);
    query.setMaxResults(limit);
    return query.getResultList();
}

From source file:it.attocchi.jpa2.JPAEntityFilter.java

public CriteriaQuery<T> getCriteria(Class<T> clazz, EntityManagerFactory emf) throws Exception {

    // CriteriaBuilder
    CriteriaBuilder criteriaBuilder = emf.getCriteriaBuilder();

    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz);
    Root<T> root = criteriaQuery.from(clazz);

    criteriaQuery.select(root);/*  w  w w  .j  a v  a  2s  .  com*/

    // criteria.where( builder.equal( personRoot.get( Utente_.eyeColor ),
    // "brown" ) );

    List<Predicate> predicateList = new ArrayList<Predicate>();

    // buildWhere(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    //
    // Predicate[] predicates = new Predicate[predicateList.size()];
    // predicateList.toArray(predicates);

    Predicate[] predicates = getWherePredicates(emf, predicateList, criteriaQuery, criteriaBuilder, root);
    Predicate wherePredicate = criteriaBuilder.and(predicates);
    criteriaQuery.where(wherePredicate);

    // buildSort(criteriaQuery, criteriaBuilder, root);
    List<Order> orders = new ArrayList<Order>();
    buildSort(orders, criteriaQuery, criteriaBuilder, root);
    if (ListUtils.isNotEmpty(orders))
        criteriaQuery.orderBy(orders);

    return criteriaQuery;
}