Example usage for javax.persistence.criteria CriteriaBuilder desc

List of usage examples for javax.persistence.criteria CriteriaBuilder desc

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder desc.

Prototype

Order desc(Expression<?> x);

Source Link

Document

Create an ordering by the descending value of the expression.

Usage

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  a va2 s  . co  m

    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:org.openmeetings.app.data.user.Organisationmanagement.java

/**
 * /*  www .j a  va 2  s .c om*/
 * @param user_level
 * @return
 */
public List<Organisation> getOrganisations(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Organisation> cq = cb.createQuery(Organisation.class);
        Root<Organisation> c = cq.from(Organisation.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<Organisation> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Organisation> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getOrganisations]", ex2);
    }
    return null;
}

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

/**
 * //w  w  w. j a va  2  s. c  om
 * @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: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 .jav a  2s.  c o  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: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;/* ww w  .  j ava  2 s  .c om*/
    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:org.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity> SearchResult<T> search(Class<T> clazz, ParseTree filterTree, int count,
        int startIndex, String sortBy, String sortOrder, FilterParser<T> filterParser) {

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<T> resourceQuery = cb.createQuery(clazz);
    Root<T> resourceRoot = resourceQuery.from(clazz);

    Subquery<Long> internalIdQuery = resourceQuery.subquery(Long.class);
    Root<T> internalIdRoot = internalIdQuery.from(clazz);
    internalIdQuery.select(internalIdRoot.get(ResourceEntity_.internalId));

    if (filterTree != null && filterTree.getChildCount() > 0) {
        Predicate predicate = filterParser.createPredicateAndJoin(filterTree, internalIdRoot);
        internalIdQuery.where(predicate);
    }/*w w w  .jav a2s .  com*/

    resourceQuery.select(resourceRoot)
            .where(cb.in(resourceRoot.get(ResourceEntity_.internalId)).value(internalIdQuery));

    // TODO: evaluate if a User-/GroupDao supplied default sortBy field is possible
    Expression<?> sortByField = resourceRoot.get(ResourceEntity_.id);

    if (sortBy != null && !sortBy.isEmpty()) {
        sortByField = filterParser.createSortByField(sortBy, resourceRoot);
    }

    // default order is ascending
    Order order = cb.asc(sortByField);

    if (sortOrder.equalsIgnoreCase("descending")) {
        order = cb.desc(sortByField);
    }

    resourceQuery.orderBy(order);

    TypedQuery<T> query = em.createQuery(resourceQuery);
    query.setFirstResult(startIndex);
    query.setMaxResults(count);

    List<T> results = query.getResultList();

    long totalResult = getTotalResults(clazz, internalIdQuery);

    return new SearchResult<>(results, totalResult);
}

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

public List<Article> findList(ArticleCategory articleCategory, Date beginDate, Date endDate, Integer first,
        Integer count) {/*from   www  .  j  a v  a2 s  .  com*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isPublication"), true));
    if (articleCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("articleCategory"), articleCategory),
                        criteriaBuilder.like(root.get("articleCategory").<String>get("treePath"),
                                "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                        + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createDate"), beginDate));
    }
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createDate"), endDate));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findList(criteriaQuery, first, count, null, null);
}

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

public Page<Article> findPage(ArticleCategory articleCategory, List<Tag> tags, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);//from www .j av  a2 s  . c  om
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isPublication"), true));
    if (articleCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("articleCategory"), articleCategory),
                        criteriaBuilder.like(root.get("articleCategory").<String>get("treePath"),
                                "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                        + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Article> subquery = criteriaQuery.subquery(Article.class);
        Root<Article> subqueryRoot = subquery.from(Article.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findPage(criteriaQuery, pageable);
}

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

public List<Article> findList(ArticleCategory articleCategory, List<Tag> tags, Integer count,
        List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Article> criteriaQuery = criteriaBuilder.createQuery(Article.class);
    Root<Article> root = criteriaQuery.from(Article.class);
    criteriaQuery.select(root);//from   w w  w . ja  va  2  s  . c o m
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isPublication"), true));
    if (articleCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("articleCategory"), articleCategory),
                        criteriaBuilder.like(root.get("articleCategory").<String>get("treePath"),
                                "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                        + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Article> subquery = criteriaQuery.subquery(Article.class);
        Root<Article> subqueryRoot = subquery.from(Article.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findList(criteriaQuery, null, count, filters, orders);
}

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

public List<Object[]> findPurchaseList(Date beginDate, Date endDate, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
    Root<Member> member = criteriaQuery.from(Member.class);
    Join<Product, Order> orders = member.join("orders");
    criteriaQuery.multiselect(member.get("id"), member.get("username"), member.get("email"),
            member.get("point"), member.get("amount"), member.get("balance"),
            criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid")));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(orders.<Date>get("createDate"), beginDate));
    }//from www . j  a v a 2s  .  c  om
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(orders.<Date>get("createDate"), endDate));
    }
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(orders.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.equal(orders.get("paymentStatus"), PaymentStatus.paid));
    criteriaQuery.where(restrictions);
    criteriaQuery.groupBy(member.get("id"), member.get("username"), member.get("email"), member.get("point"),
            member.get("amount"), member.get("balance"));
    criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid"))));
    TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (count != null && count >= 0) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}