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.saake.invoicer.sessionbean.PurchaseOrderFacade.java

@Override
public List<PurchaseOrder> findAll() {

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

    Root<PurchaseOrder> root = cq.from(PurchaseOrder.class);
    cq.select(root);//from ww w.ja  v a2 s  .c  om

    ParameterExpression<String> status = cb.parameter(String.class);

    //        cq.where(cb.notEqual(invRoot.get("status"), status));
    cq.where(cb.notEqual(root.get("deleted"), 'Y'));
    cq.orderBy(cb.desc(root.get("purchaseOrderId")));
    Query query = getEntityManager().createQuery(cq);
    //        query.setParameter(status, PaymentStatusEnum.DELETE.getValue());

    List<PurchaseOrder> list = query.getResultList();

    for (PurchaseOrder wo : list) {
        List<PurchaseOrderItems> tempDel = new ArrayList<>();
        for (PurchaseOrderItems wot : wo.getPurchaseOrderItems()) {
            if (wot.isDeleted()) {
                tempDel.add(wot);
            }
        }
        wo.getPurchaseOrderItems().removeAll(tempDel);
    }
    return list;
}

From source file:com.aimdek.ccm.dao.impl.UserRepositoryImpl.java

/**
 * Adds the sorting./*from  www  .j  av a2  s .  c  o  m*/
 *
 * @param sortField the sort field
 * @param sortOrder the sort order
 * @param query the query
 * @param builder the builder
 * @param root the root
 */
private void addSorting(String sortField, String sortOrder, CriteriaQuery<User> query, CriteriaBuilder builder,
        Root<User> root) {
    boolean isSet = FALSE;
    if (CommonUtil.isNotNull(sortField) && !sortField.contains(FIELDCONSTANT_CARDNUMBER)
            && !sortField.contains(FIELDCONSTANT_CREDITLIMIT) && !sortField.contains(FIELDCONSTANT_BALANCE)) {
        isSet = TRUE;
        if (sortOrder.startsWith(SORT_ORDER_ASCENDING)) {
            query.orderBy(builder.asc(root.get(sortField)));
        } else {
            query.orderBy(builder.desc(root.get(sortField)));
        }
    }
    if (!isSet) {
        query.orderBy(builder.desc(root.get(FIELD_CONSTANT_CREATED_AT)));
    }
}

From source file:org.openmeetings.app.data.basic.dao.LdapConfigDaoImpl.java

public List<LdapConfig> getLdapConfigs(int start, int max, String orderby, boolean asc) {
    try {/* w  w  w  .ja v a2  s  . com*/
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<LdapConfig> cq = cb.createQuery(LdapConfig.class);
        Root<LdapConfig> c = cq.from(LdapConfig.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<LdapConfig> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<LdapConfig> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getLdapConfigs]", ex2);
    }
    return null;
}

From source file:cl.troncador.delfin.query.constraint.PrepareOrderAdapter.java

public Order[] getOrderArray(Root<T> root, CriteriaBuilder criteriaBuilder) {
    List<Order> orderList = new ArrayList<Order>();

    for (Pair<SingularAttribute<T, ?>, Direction> directionedColumn : directionedColumnList) {
        Direction direction = directionedColumn.getRight();
        SingularAttribute<T, ?> column = directionedColumn.getLeft();
        Path<?> path = root.get(column);
        Order order = null;//  ww w. ja va2  s .  co  m
        switch (direction) {
        case ASC:
            order = criteriaBuilder.asc(path);
            break;
        case DES:
            order = criteriaBuilder.desc(path);
            break;
        }
        orderList.add(order);
    }
    return orderList.toArray(new Order[orderList.size()]);
}

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

/**
 * Get the latest date of measurement snapshots
 * @return/*from   w  w w  .  j  a  v  a2  s. c o  m*/
 */
public Date getLatestDate() {
    logger.info("Get the latest date from JIRA measurements...");
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<JiraMetricMeasurement> query = cb.createQuery(JiraMetricMeasurement.class);
    Root<JiraMetricMeasurement> root = query.from(JiraMetricMeasurement.class);
    query.select(root);
    query.orderBy(cb.desc(root.get(JiraMetricMeasurement_.timeStamp)));
    Date latest;
    try {
        JiraMetricMeasurement m = em.createQuery(query).setMaxResults(1).getSingleResult();
        latest = m.getTimeStamp();
    } catch (NoResultException nre) {
        latest = null;
    }
    return latest;
}

From source file:org.synyx.hades.dao.orm.GenericJpaDao.java

private List<Order> toOrders(Sort sort, Root<T> root, CriteriaBuilder cb) {

    List<Order> orders = new ArrayList<Order>();

    if (sort == null) {
        return orders;
    }/* w  w  w . j a v  a  2s .c o m*/

    for (Property property : sort) {
        Expression<?> expression = root.get(property.getName());
        orders.add(property.isAscending() ? cb.asc(expression) : cb.desc(expression));

    }

    return orders;
}

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 w  ww .jav a  2  s.  c o m

    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:eu.uqasar.service.dataadapter.CubesDataService.java

/**
 * Get the latest date of measurement snapshots
 * @return/*from   w ww.  java  2s. com*/
 */
private Date getLatestDate() {
    logger.info("Get the latest date from CUBES measurements...");
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<CubesMetricMeasurement> query = cb.createQuery(CubesMetricMeasurement.class);
    Root<CubesMetricMeasurement> root = query.from(CubesMetricMeasurement.class);
    query.select(root);
    query.orderBy(cb.desc(root.get(CubesMetricMeasurement_.timeStamp)));
    return em.createQuery(query).setMaxResults(1).getSingleResult().getTimeStamp();
}

From source file:org.openmeetings.app.data.basic.Configurationmanagement.java

public List<Configuration> getConfigurations(int start, int max, String orderby, boolean asc) {
    try {// w  ww  . j a  v a2 s .  com
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Configuration> cq = cb.createQuery(Configuration.class);
        Root<Configuration> c = cq.from(Configuration.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<Configuration> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Configuration> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getConfigurations]", ex2);
    }
    return null;
}

From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java

/**
 * @see ??JPA//from www  . j  ava 2s .com
 * @param filters
 * @param entityClazz
 * @param isDistinct  trueSQLdistinctfalse?
 * @return
 */
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) {
    return new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (orderParams != null && orderParams.size() > 0) {
                /*
                CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
                Root<Foo> from = criteriaQuery.from(Foo.class);
                CriteriaQuery<Foo> select = criteriaQuery.select(from);
                criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
                */
                List<Order> orders = new ArrayList<Order>(orderParams.size());
                for (OrderParam orderParam : orderParams) {
                    if (orderParam != null && orderParam.getField() != null) {
                        String fields[] = StringUtil.split(orderParam.getField(), '.');
                        Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]);
                        for (int i = 1, len = fields.length; i < len; ++i) {
                            expression = expression.get(fields[i]);
                        }
                        if (expression != null) {
                            Order order = (orderParam.getType() == null
                                    || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression)
                                            : builder.desc(expression);
                            orders.add(order);
                            //                        query.orderBy(order);
                        }
                    }
                }
                query.orderBy(orders);
            }
            query.distinct(isDistinct);
            if (Collections3.isNotEmpty(filters)) {
                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, '.');
                    Path expression = null;

                    //////  ?
                    boolean hasJoin = names[0].startsWith("[join]");
                    String fn = hasJoin ? names[0].substring(6) : names[0];
                    boolean isNotDateType = !(filter.value instanceof Date);
                    try {
                        expression = hasJoin ? root.join(fn) : root.get(fn);
                        if (isNotDateType && isDateType(expression.getJavaType())) {
                            // filter.value??
                            filter.value = parseDate(filter.value.toString(), filter.operator);
                        }
                    } catch (Exception e) {
                        //                     logger.error(e.getMessage(), e);
                        continue; // ??
                    }
                    boolean isPropertyNotValid = false;
                    for (int i = 1; i < names.length; i++) {
                        try {
                            expression = expression.get(names[i]);
                            if (isNotDateType && isDateType(expression.getJavaType())) {
                                filter.value = parseDate(filter.value.toString(), filter.operator);
                            }
                        } catch (Exception e) {
                            //                        logger.error(e.getMessage(), e);
                            isPropertyNotValid = true; // 
                            break; // ??
                        }
                    }
                    if (expression == null || isPropertyNotValid) {
                        continue;
                    }
                    ///////

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ORLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.or(like));
                        }

                        break;
                    case ANDLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case ANDNOTLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notLike(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case OREQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.equal(expression, values[i]);
                            }
                            predicates.add(builder.or(like));
                        }
                        break;

                    case ANDNOTEQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notEqual(expression, values[i]);
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case NOTEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    case NOTLIKE:
                        predicates.add(builder.notLike(expression, "%" + filter.value + "%"));
                        break;
                    case NULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NOTNULL:
                        predicates.add(builder.isNotNull(expression));
                        break;
                    //                  case IN:
                    //                     predicates.add(builder.in(expression).in(values));
                    //                     break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}