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.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Add the {@link SystemUserLogType} to the database.
 *
 * @param log//from   w  ww . ja  v a 2  s. c o m
 *            the {@link SystemUserLogType} to add.
 */
private void addChannelInvocation(final SystemUserLogType log) {
    /* Setup context and version. */
    log.setContext(this.getContextName());
    log.setVersion(this.getContextVersion());
    if (log.getUserName() != null && log.getUserName().trim().length() == 0) {
        log.setUserName(null);
    }

    /* Setup to search existing one. */
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<SystemUserLogType> q = cb.createQuery(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);

    final List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.context), log.getContext()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.version), log.getVersion()));
    if (log.getUserName() == null) {
        predicates.add(cb.isNull(c.<String>get(SystemUserLogType_.userName)));
    } else {
        predicates.add(cb.equal(c.<String>get(SystemUserLogType_.userName), log.getUserName()));
    }
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.serviceName), log.getServiceName()));
    predicates.add(cb.equal(c.<String>get(SystemUserLogType_.operationName), log.getOperationName()));
    predicates.add(cb.between(c.<Date>get(SystemUserLogType_.logDateItem), getDayStart(log.getLogDateItem()),
            getDayEnd(log.getLogDateItem())));

    q.where(predicates.toArray(new Predicate[predicates.size()]));
    q.orderBy(cb.desc(c.<Long>get(SystemUserLogType_.hjid)));
    TypedQuery<SystemUserLogType> typedQuery = this.em.createQuery(q);

    SystemUserLogType persistence = null;
    synchronized (StatisticsLoggingDao.class) {
        try {
            persistence = typedQuery.getSingleResult();
            if (persistence == null) {
                /* Not found -> persist */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            } else {
                /* Found -> add and merge */
                this.setupSystemUserLog(persistence, log);
                this.em.merge(persistence);
            }
        } catch (final NoResultException e) {
            /* Not found -> persist */
            persistence = log;
            this.setupSystemUserLog(persistence, null);
            this.em.persist(persistence);
        } catch (final NonUniqueResultException e) {
            /* Found more */
            typedQuery = this.em.createQuery(q);
            final List<SystemUserLogType> list = typedQuery.getResultList();
            SystemUserLogType l;
            for (int i = 0; i < list.size(); i++) {
                l = list.get(i);
                if (persistence == null && l.getHjid() != null) {
                    persistence = l;
                    break;
                }
            }
            if (persistence != null) {
                /* Found more -> condense to first valid one -> merge. */
                this.setupSystemUserLog(persistence, log);
                for (int i = list.size() - 1; i >= 0; i--) {
                    l = list.get(i);
                    if (l != null && l.getHjid() != null) {
                        if (persistence.getHjid().equals(l.getHjid())) {
                        } else {
                            this.setupSystemUserLog(persistence, l);
                            list.remove(i);
                            this.em.remove(l);
                        }
                    }
                }
                this.em.merge(persistence);
            } else {
                /* Found more -> no valid one in list -> persist. */
                persistence = log;
                this.setupSystemUserLog(persistence, null);
                this.em.persist(persistence);
            }
        }
    }
    this.logger.debug("addChannelInvocation SystemUserLog {} {} {} {} {} {}",
            this.contextNameProvider.getContextName(), this.contextNameProvider.getContextVersion(),
            String.valueOf(persistence.getUserName()), persistence.getServiceName(),
            persistence.getOperationName(), persistence.getLogDate().toXMLFormat());
}

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

public List<Article> findList(ArticleCategory articleCategory, Tag tag, Boolean isPublication, 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);/* www  .j  a  v  a 2 s. co  m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (articleCategory != null) {
        Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class);
        Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory),
                criteriaBuilder.like(subqueryRoot.<String>get("treePath"),
                        "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.in(root.get("articleCategory")).value(subquery));
    }
    if (tag != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag));
    }
    if (isPublication != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isPublication"), isPublication));
    }
    criteriaQuery.where(restrictions);
    if (orders == null || orders.isEmpty()) {
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")),
                criteriaBuilder.desc(root.get("createDate")));
    }
    return super.findList(criteriaQuery, null, count, filters, orders);
}

From source file:de.whs.poodle.repositories.StatisticsRepository.java

public List<Statistic> getStatistics(FeedbackSearchCriteria s, int instructorId, int limit) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Statistic> cq = cb.createQuery(Statistic.class);
    Root<Statistic> statistic = cq.from(Statistic.class);

    /* fetch the exercises immediately so they don't have to
     * be lazy-fetched one by one while rendering the table rows. */
    statistic.fetch("exercise");

    // join we need to match the course
    Join<Statistic, Course> course = statistic.join("courseTerm").join("course");

    // create empty "and" predicate
    Predicate where = cb.conjunction();

    // only non-empty
    Predicate notEmpty = cb.isFalse(statistic.get("empty"));
    where = cb.and(where, notEmpty);/*from   w  w w . ja  v  a2 s .co m*/

    // only statistics for courses that the instructor has access to
    Predicate hasInstructorAccessToCourse = cb.isTrue(cb.function("has_instructor_access_to_course",
            Boolean.class, course.get("id"), cb.literal(instructorId)));

    where = cb.and(where, hasInstructorAccessToCourse);

    // filter by courseId
    if (s.getCourseId() != 0) {
        Predicate courseMatches = cb.equal(course.get("id"), s.getCourseId());
        where = cb.and(where, courseMatches);
    }

    // filter by student
    if (s.getStudent() != null) {
        Predicate studentMatches = cb.equal(statistic.get("student").get("id"), s.getStudent().getId());
        where = cb.and(where, studentMatches);
    }

    cq.where(where);

    // order by date
    cq.orderBy(cb.desc(statistic.get("completedAt")));

    return em.createQuery(cq).setMaxResults(limit).getResultList();
}

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

public List<Product> search(String keyword, Boolean isGift, Integer count) {
    if (StringUtils.isEmpty(keyword)) {
        return Collections.<Product>emptyList();
    }/*from www  . j  a  v a 2 s  . co m*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (pattern.matcher(keyword).matches()) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("id"), Long.valueOf(keyword)),
                        criteriaBuilder.like(root.<String>get("sn"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.<String>get("fullName"), "%" + keyword + "%")));
    } else {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.like(root.<String>get("sn"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.<String>get("fullName"), "%" + keyword + "%")));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    criteriaQuery.where(restrictions);
    criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")));
    return super.findList(criteriaQuery, null, count, null, null);
}

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

public Page<Article> findPage(ArticleCategory articleCategory, Tag tag, Boolean isPublication,
        Pageable pageable) {/*from  w  w  w  .ja v  a2  s.c o  m*/
    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();
    if (articleCategory != null) {
        Subquery<ArticleCategory> subquery = criteriaQuery.subquery(ArticleCategory.class);
        Root<ArticleCategory> subqueryRoot = subquery.from(ArticleCategory.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.or(criteriaBuilder.equal(subqueryRoot, articleCategory),
                criteriaBuilder.like(subqueryRoot.<String>get("treePath"),
                        "%" + ArticleCategory.TREE_PATH_SEPARATOR + articleCategory.getId()
                                + ArticleCategory.TREE_PATH_SEPARATOR + "%")));
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.in(root.get("articleCategory")).value(subquery));
    }
    if (tag != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.join("tags"), tag));
    }
    if (isPublication != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isPublication"), isPublication));
    }
    criteriaQuery.where(restrictions);
    if (pageable == null
            || ((StringUtils.isEmpty(pageable.getOrderProperty()) || pageable.getOrderDirection() == null)
                    && CollectionUtils.isEmpty(pageable.getOrders()))) {
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("isTop")),
                criteriaBuilder.desc(root.get("createDate")));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:eu.domibus.common.dao.MessageLogDao.java

public List<MessageLogEntry> findPaged(int from, int max, String column, boolean asc,
        HashMap<String, Object> filters) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<MessageLogEntry> cq = cb.createQuery(MessageLogEntry.class);
    Root<MessageLogEntry> mle = cq.from(MessageLogEntry.class);
    cq.select(mle);/*from  w  w w  .  j a v  a 2  s  . co  m*/
    List<Predicate> predicates = new ArrayList<Predicate>();
    for (Map.Entry<String, Object> filter : filters.entrySet()) {
        if (filter.getValue() != null) {
            if (filter.getValue() instanceof String) {
                if (!filter.getValue().toString().isEmpty()) {
                    switch (filter.getKey().toString()) {
                    case "receivedFrom":
                        predicates.add(cb.greaterThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    case "receivedTo":
                        predicates.add(cb.lessThanOrEqualTo(mle.<Date>get("received"),
                                Timestamp.valueOf(filter.getValue().toString())));
                        break;
                    default:
                        predicates.add(cb.like(mle.<String>get(filter.getKey()), (String) filter.getValue()));
                        break;
                    }
                }
            } else {
                predicates.add(cb.equal(mle.<String>get(filter.getKey()), filter.getValue()));
            }
        }
    }
    cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
    if (column != null) {
        if (asc) {
            cq.orderBy(cb.asc(mle.get(column)));
        } else {
            cq.orderBy(cb.desc(mle.get(column)));
        }

    }
    final TypedQuery<MessageLogEntry> query = this.em.createQuery(cq);
    query.setFirstResult(from);
    query.setMaxResults(max);
    return query.getResultList();
}

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

/**
 * {@inheritDoc}/*from  w  w w. j  a  v a 2 s . c  o 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:net.groupbuy.dao.impl.ProductDaoImpl.java

public List<Product> findList(ProductCategory productCategory, Date beginDate, Date endDate, Integer first,
        Integer count) {/*ww w  .  ja v a 2 s .com*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isMarketable"), true));
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.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:org.openmeetings.app.data.conference.Roommanagement.java

/**
 * gets a list of all availible rooms/*  ww  w  .  j  a v  a2  s  .c  o m*/
 * 
 * @param user_level
 * @param start
 * @param max
 * @param orderby
 * @param asc
 * @return
 */
public List<Rooms> getRoomsInternatl(int start, int max, String orderby, boolean asc) {
    try {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Rooms> cq = cb.createQuery(Rooms.class);
        Root<Rooms> c = cq.from(Rooms.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<Rooms> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<Rooms> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getRooms ] ", ex2);
    }
    return null;
}

From source file:com.hiperium.dao.common.generic.GenericDAO.java

/**
 * Sets the criteria parameters for searching execution.
 *
 * @param entity//ww w .  j ava  2 s.  com
 *            the entity with the values for the criteria.
 * @param fieldsToSort
 *            the fields to sort the result.
 */
private <E> CriteriaQuery<E> configureCriteria(E entity, Class<E> entityClass, String... fieldsToSort) {
    CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<E> root = criteriaQuery.from(entityClass);
    criteriaQuery.select(root);
    this.constructQuery(criteriaBuilder, criteriaQuery, root, entity);
    Order[] orderCriteriaList = null;
    if (fieldsToSort.length > 0) {
        orderCriteriaList = new Order[fieldsToSort.length];
        for (int i = 0; i < fieldsToSort.length; i++) {
            if (fieldsToSort[i].startsWith("A,")) {
                if (fieldsToSort[i].contains(".")) {
                    String compositeValue = fieldsToSort[i].substring(2);
                    String compositeName = compositeValue.split("\\.")[0];
                    String compositeFieldName = compositeValue.split("\\.")[1];
                    orderCriteriaList[i] = criteriaBuilder.asc(root.get(compositeName).get(compositeFieldName));
                } else {
                    orderCriteriaList[i] = criteriaBuilder.asc(root.get(fieldsToSort[i].substring(2)));
                }
            } else if (fieldsToSort[i].startsWith("D,")) {
                if (fieldsToSort[i].contains(".")) {
                    String compositeValue = fieldsToSort[i].substring(2);
                    String compositeName = compositeValue.split("\\.")[0];
                    String compositeFieldName = compositeValue.split("\\.")[1];
                    orderCriteriaList[i] = criteriaBuilder
                            .desc(root.get(compositeName).get(compositeFieldName));
                } else {
                    orderCriteriaList[i] = criteriaBuilder.desc(root.get(fieldsToSort[i].substring(2)));
                }
            }
        }
    } else {
        List<String> ids = this.getIdFields(entity);
        orderCriteriaList = new Order[ids.size()];
        int i = 0;
        for (String id : ids) {
            if (id.startsWith(PK_OBJECT_NAME)) {
                String compositeFieldName = id.replace(PK_OBJECT_NAME.concat("."), "");
                orderCriteriaList[i] = criteriaBuilder.asc(root.get(PK_OBJECT_NAME).get(compositeFieldName));
            } else {
                orderCriteriaList[i] = criteriaBuilder.asc(root.get(id));
            }
            i = i + 1;
        }
    }
    criteriaQuery.orderBy(orderCriteriaList);
    return criteriaQuery;
}