Example usage for javax.persistence.criteria CriteriaBuilder asc

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

Introduction

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

Prototype

Order asc(Expression<?> x);

Source Link

Document

Create an ordering by the ascending value of the expression.

Usage

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

private void addOrders(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    if (criteriaQuery == null || pageable == null) {
        return;/*from w  w  w  .  jav a  2s.  co m*/
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    List<javax.persistence.criteria.Order> orderList = new ArrayList<javax.persistence.criteria.Order>();
    if (!criteriaQuery.getOrderList().isEmpty()) {
        orderList.addAll(criteriaQuery.getOrderList());
    }
    if (StringUtils.isNotEmpty(pageable.getOrderProperty()) && pageable.getOrderDirection() != null) {
        if (pageable.getOrderDirection() == Direction.asc) {
            orderList.add(criteriaBuilder.asc(root.get(pageable.getOrderProperty())));
        } else if (pageable.getOrderDirection() == Direction.desc) {
            orderList.add(criteriaBuilder.desc(root.get(pageable.getOrderProperty())));
        }
    }
    if (pageable.getOrders() != null) {
        for (Order order : pageable.getOrders()) {
            if (order.getDirection() == Direction.asc) {
                orderList.add(criteriaBuilder.asc(root.get(order.getProperty())));
            } else if (order.getDirection() == Direction.desc) {
                orderList.add(criteriaBuilder.desc(root.get(order.getProperty())));
            }
        }
    }
    criteriaQuery.orderBy(orderList);
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

private List<String> getFlowProcessTypeIds(final String modelVersion, final String flowId) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<String> q = cb.createQuery(String.class);
    final Root<FlowProcessType> f = q.from(FlowProcessType.class);

    q.select(f.<String>get(FlowProcessType_.id));
    q.where(cb.equal(f.<String>get(FlowProcessType_.modelVersion), modelVersion),
            cb.equal(f.<String>get(FlowProcessType_.parentId), flowId));
    q.orderBy(cb.asc(f.<Long>get(FlowProcessType_.hjid)));
    final TypedQuery<String> typedQuery = this.em.createQuery(q);
    final List<String> value = typedQuery.getResultList();
    return value;
}

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

public List<ActivityAIPC> itemsDateRange(Date start, Date end, int[] range) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(ActivityAIPC.class);
    Root<ActivityAIPC> rt = cq.from(ActivityAIPC.class);
    cq.where(cb.and(rt.get(ActivityAIPC_.fromdateofservice).isNotNull(),
            cb.and(cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 528),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 529),
                    cb.notEqual(rt.get(ActivityAIPC_.procedurecodeser), 530),
                    cb.between(rt.get(ActivityAIPC_.fromdateofservice), start, end))));
    cq.orderBy(cb.asc(rt.get(ActivityAIPC_.fromdateofservice)));
    Query q = em.createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);/* w  w w .j av  a2 s  . c o m*/
    return q.getResultList();

}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Get the list of {@link DataType} with the ids.
 *
 * @param modelVersion//  w w w  . j  a va  2  s .  co m
 *            the model version.
 * @param ids
 *            the list of ids to return.
 * @return the list of {@link DataType}.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public List<DataType> getDataTypesById(final String modelVersion, final List<String> ids) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<DataType> q = cb.createQuery(DataType.class);
    final Root<DataType> f = q.from(DataType.class);
    final Predicate orIds = cb.disjunction();
    ids.stream().forEach(id -> orIds.getExpressions().add(cb.equal(f.<String>get(DataType_.id), id)));
    q.where(cb.equal(f.<String>get(DataType_.modelVersion), modelVersion), orIds);
    q.orderBy(cb.asc(f.<String>get(DataType_.name)), cb.asc(f.<String>get(DataType_.id)));
    final TypedQuery<DataType> typedQuery = this.em.createQuery(q);
    final List<DataType> value = typedQuery.getResultList();
    value.stream().forEach(dt -> EagerLoader.load(dt));
    return value;
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private List<ImageProductDTO> getImageProductDTOs() {
    return transactionTemplate.execute(new TransactionCallback<List<ImageProductDTO>>() {
        @Override/*from   www  .  j a  v  a2 s. c  o  m*/
        public List<ImageProductDTO> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<ImageProductDTO> query = cb.createQuery(ImageProductDTO.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            query.select(cb.construct(ImageProductDTO.class, imageRoot.get(Image_.name),
                    productJoin.get(Product_.name))).orderBy(cb.asc(imageRoot.get(Image_.name)));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

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  va  2  s .c  o 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

/**
 * /*w w w  .  jav  a 2 s .c  o m*/
 * @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: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   www .  j av 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: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.// ww  w  .  jav  a2  s.  com
 */
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: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);
    }/*from  ww w .j  av  a 2  s .  c  om*/

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