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:org.apache.openmeetings.data.user.UserManager.java

/**
 * suche eines Bentzers//from   w  ww. ja va  2  s.c  om
 * 
 * @param user_level
 * @param searchstring
 * @param max
 * @param start
 * @return
 */
public List<User> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start,
        String orderby, boolean asc) {
    if (authLevelUtil.checkAdminLevel(user_level)) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<User> cq = cb.createQuery(User.class);
            Root<User> c = cq.from(User.class);
            Expression<String> literal = cb.literal("%" + searchstring + "%");
            Path<String> path = c.get(searchcriteria);
            Predicate predicate = cb.like(path, literal);
            Predicate condition = cb.notEqual(c.get("deleted"), true);
            cq.where(condition, predicate);
            cq.distinct(asc);
            if (asc) {
                cq.orderBy(cb.asc(c.get(orderby)));
            } else {
                cq.orderBy(cb.desc(c.get(orderby)));
            }
            TypedQuery<User> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<User> contactsZ = q.getResultList();
            return contactsZ;
        } catch (Exception ex2) {
            log.error("searchUser", ex2);
        }
    }
    return null;
}

From source file:org.apache.ranger.service.XTrxLogService.java

@Override
public VXTrxLogList searchXTrxLogs(SearchCriteria searchCriteria) {
    EntityManager em = daoMgr.getEntityManager();
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<VXXTrxLog> selectCQ = criteriaBuilder.createQuery(VXXTrxLog.class);
    Root<VXXTrxLog> rootEntityType = selectCQ.from(VXXTrxLog.class);
    Predicate predicate = generatePredicate(searchCriteria, em, criteriaBuilder, rootEntityType);

    selectCQ.where(predicate);//from  ww  w  .ja v  a  2s.c o  m
    if ("asc".equalsIgnoreCase(searchCriteria.getSortType())) {
        selectCQ.orderBy(criteriaBuilder.asc(rootEntityType.get("createTime")));
    } else {
        selectCQ.orderBy(criteriaBuilder.desc(rootEntityType.get("createTime")));
    }
    int startIndex = searchCriteria.getStartIndex();
    int pageSize = searchCriteria.getMaxRows();
    List<VXXTrxLog> resultList = em.createQuery(selectCQ).setFirstResult(startIndex).setMaxResults(pageSize)
            .getResultList();

    List<VXTrxLog> trxLogList = new ArrayList<VXTrxLog>();
    for (VXXTrxLog xTrxLog : resultList) {
        VXTrxLog trxLog = mapCustomViewToViewObj(xTrxLog);

        if (trxLog.getUpdatedBy() != null) {
            XXPortalUser xXPortalUser = rangerDaoManager.getXXPortalUser()
                    .getById(Long.parseLong(trxLog.getUpdatedBy()));
            if (xXPortalUser != null) {
                trxLog.setOwner(xXPortalUser.getLoginId());
            }
        }

        trxLogList.add(trxLog);
    }

    VXTrxLogList vxTrxLogList = new VXTrxLogList();
    vxTrxLogList.setStartIndex(startIndex);
    vxTrxLogList.setPageSize(pageSize);
    vxTrxLogList.setVXTrxLogs(trxLogList);
    return vxTrxLogList;
}

From source file:org.apache.rave.portal.repository.impl.JpaWidgetRepository.java

private Order getOrderByTitleAsc(CriteriaBuilder cb, Root<JpaWidget> widgetType) {
    return cb.asc(getTitleField(widgetType));
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

@SuppressWarnings("unchecked")
public <T extends IBean> T[] findByValue(Class<T> beansInterface, String name, Object value, String orderBy,
        boolean ascending) {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }//from  www .  ja  va 2  s  .  c  o  m

    // validate bean interface
    Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface);
    if (beanClass == null) {
        throw new IllegalArgumentException("Invalid bean interface specified");
    }

    // get persistent beans by criteria
    try {
        // construct query criteria
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass);
        Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass);
        if (name != null) {
            criteriaQuery.where((value != null) ? criteriaBuilder.equal(beanRoot.get(name), value)
                    : criteriaBuilder.isNull(beanRoot.get(name)));
        }
        if (orderBy != null) {
            criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy))
                    : criteriaBuilder.desc(beanRoot.get(orderBy)));
        }

        // invoke query
        Query query = entityManager.createQuery(criteriaQuery);
        List<? extends IBean> beansList = query.getResultList();
        if ((beansList != null) && !beansList.isEmpty()) {
            return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size()));
        }
    } catch (Exception e) {
        logger.error("Unexpected exception: " + e, e);
    }
    return (T[]) Array.newInstance(beansInterface, 0);
}

From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java

@SuppressWarnings("unchecked")
public <T extends IBean> T[] findByValues(Class<T> beansInterface, Map<String, Object> values, String orderBy,
        boolean ascending) {
    // validate entity manager transaction
    if (entityManager == null) {
        throw new IllegalStateException("Transaction not initiated or already closed");
    }/*from w w  w.  ja  v  a  2s  . co m*/

    // validate bean interface
    Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface);
    if (beanClass == null) {
        throw new IllegalArgumentException("Invalid bean interface specified");
    }

    // get persistent beans by criteria
    try {
        // construct query criteria
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass);
        Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass);
        if ((values != null) && !values.isEmpty()) {
            Predicate predicate = null;
            for (Map.Entry<String, Object> value : values.entrySet()) {
                Predicate valuePredicate = ((value.getValue() != null)
                        ? criteriaBuilder.equal(beanRoot.get(value.getKey()), value.getValue())
                        : criteriaBuilder.isNull(beanRoot.get(value.getKey())));
                predicate = ((predicate != null) ? criteriaBuilder.and(predicate, valuePredicate)
                        : valuePredicate);
            }
            criteriaQuery.where(predicate);
        }
        if (orderBy != null) {
            criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy))
                    : criteriaBuilder.desc(beanRoot.get(orderBy)));
        }

        // invoke query
        Query query = entityManager.createQuery(criteriaQuery);
        List<? extends IBean> beansList = query.getResultList();
        if ((beansList != null) && !beansList.isEmpty()) {
            return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size()));
        }
    } catch (Exception e) {
        logger.error("Unexpected exception: " + e, e);
    }
    return (T[]) Array.newInstance(beansInterface, 0);
}

From source file:org.apereo.portal.i18n.dao.jpa.JpaMessageDao.java

@Override
public void afterPropertiesSet() throws Exception {
    this.codeParameter = this.createParameterExpression(String.class, "code");
    this.localeParameter = this.createParameterExpression(Locale.class, "locale");

    this.findMessageByCodeAndLocaleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override//from  w  w  w. jav  a 2s.  co  m
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.and(cb.equal(root.get(MessageImpl_.code), codeParameter),
                            cb.equal(root.get(MessageImpl_.locale), localeParameter)));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.code)),
                            cb.asc(root.get(MessageImpl_.locale)));

                    return criteriaQuery;
                }
            });

    this.findMessageByCodeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.equal(root.get(MessageImpl_.code), codeParameter));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.locale)));

                    return criteriaQuery;
                }
            });

    this.findMessageByLocaleQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MessageImpl>>() {
                @Override
                public CriteriaQuery<MessageImpl> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<MessageImpl> criteriaQuery = cb.createQuery(MessageImpl.class);
                    final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
                    criteriaQuery.select(root);
                    criteriaQuery.where(cb.equal(root.get(MessageImpl_.locale), localeParameter));
                    criteriaQuery.orderBy(cb.asc(root.get(MessageImpl_.code)));

                    return criteriaQuery;
                }
            });

    this.findCodes = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<String>>() {
        @Override
        public CriteriaQuery<String> apply(CriteriaBuilder cb) {
            final CriteriaQuery<String> criteriaQuery = cb.createQuery(String.class);
            final Root<MessageImpl> root = criteriaQuery.from(MessageImpl.class);
            criteriaQuery.select(root.get(MessageImpl_.code));
            criteriaQuery.groupBy(root.get(MessageImpl_.code));
            return criteriaQuery;
        }
    });
}

From source file:org.broadleafcommerce.core.catalog.dao.IndexFieldCustomPersistenceHandler.java

@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto,
        DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {

    FilterAndSortCriteria fieldFsc = cto.getCriteriaMap().get("field");
    if (fieldFsc != null) {
        List<String> filterValues = fieldFsc.getFilterValues();
        boolean didFilter = false;
        cto.getCriteriaMap().remove("field");

        CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
        CriteriaQuery<IndexField> criteria = builder.createQuery(IndexField.class);
        Root<IndexFieldImpl> root = criteria.from(IndexFieldImpl.class);
        criteria.select(root);/*from   w w w.j  a va 2 s .  co m*/

        // Check if we are searching for specific field names
        List<Predicate> restrictions = new ArrayList<Predicate>();
        if (CollectionUtils.isNotEmpty(filterValues)) {
            restrictions.add(builder.like(root.get("field").<String>get("friendlyName"),
                    "%" + filterValues.get(0) + "%"));
            didFilter = true;
        }

        // Check if this filter value has a sort direction associated with it
        Order order = null;
        for (FilterAndSortCriteria sortCriteria : cto.getCriteriaMap().values()) {
            if (sortCriteria.getSortDirection() != null) {
                Path path = root;
                try {
                    // Try to find the path to the property in IndexFieldImpl
                    String[] pathParts = sortCriteria.getPropertyId().split("\\.");
                    for (String part : pathParts) {
                        path = path.get(part);
                    }

                    // If we made it here, we have the path, set the sorting (asc/desc)
                    if (sortCriteria.getSortAscending()) {
                        order = builder.asc(path);
                    } else {
                        order = builder.desc(path);
                    }
                    criteria.orderBy(order);
                    break;
                } catch (IllegalArgumentException e) {
                    // This isn't an actual entity property
                    continue;
                }
            }
        }

        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

        TypedQuery<IndexField> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);
        List<IndexField> indexFields = query.getResultList();

        // Convert the result list into a list of entities
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        Map<String, FieldMetadata> indexFieldMetadata = helper
                .getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective);
        Entity[] entities = helper.getRecords(indexFieldMetadata, indexFields);

        // We need to get the total number of records available because the entityList returned may not be the full set.
        Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(IndexField.class.getName(),
                persistencePerspective);
        List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto,
                IndexField.class.getName(), originalProps);
        int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(),
                filterMappings);

        // Create a Dynamic Result Set from the entity list created above.
        DynamicResultSet resultSet = new DynamicResultSet(entities,
                (didFilter ? entities.length : totalRecords));
        return resultSet;
    }

    DynamicResultSet resultSet = helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto);
    return resultSet;
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachOrderBy(SearchCriteria searchCriteria, From<?, ? extends Product> product,
        Path<? extends Sku> sku, CriteriaQuery<?> criteria) {
    if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
        CriteriaBuilder builder = em.getCriteriaBuilder();

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

        String sortQueries = searchCriteria.getSortQuery();
        for (String sortQuery : sortQueries.split(",")) {
            String[] sort = sortQuery.split(" ");
            if (sort.length == 2) {
                String key = sort[0];
                boolean asc = sort[1].toLowerCase().contains("asc");

                // Determine whether we should use the product path or the sku path
                Path<?> pathToUse;
                if (key.contains("defaultSku.")) {
                    pathToUse = sku;/*from  ww w .  j a va2  s  .  c o m*/
                    key = key.substring("defaultSku.".length());
                } else if (key.contains("product.")) {
                    pathToUse = product;
                    key = key.substring("product.".length());
                } else {
                    // We don't know which path this facet is built on - resolves previous bug that attempted
                    // to attach search facet to any query parameter
                    continue;
                }

                if (asc) {
                    sorts.add(builder.asc(pathToUse.get(key)));
                } else {
                    sorts.add(builder.desc(pathToUse.get(key)));
                }
            }
        }

        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
    }
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected CriteriaQuery<Product> getCriteriaForActiveProducts(Date currentDate) {
    // Set up the criteria query that specifies we want to return Products
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Product> criteria = builder.createQuery(Product.class);

    // The root of our search is Product
    Root<ProductImpl> product = criteria.from(ProductImpl.class);

    // We need to filter on active date on the sku
    Join<Product, Sku> sku = product.join("defaultSku");
    product.fetch("defaultSku");

    // Product objects are what we want back
    criteria.select(product);//from   www. ja  v  a2s. c  om

    // Ensure the product is currently active
    List<Predicate> restrictions = new ArrayList<Predicate>();
    attachActiveRestriction(currentDate, product, sku, restrictions);

    // Add the restrictions to the criteria query
    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

    //Add ordering so that paginated queries are consistent
    criteria.orderBy(builder.asc(product.get("id")));
    return criteria;
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java

@SuppressWarnings("unchecked")
protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity,
        List<FilterMapping> filterMappings, boolean isCount, boolean isMax, Integer firstResult,
        Integer maxResults, String maxField) {

    CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();

    Class<Serializable> ceilingMarker;
    try {/*from   w  w  w  .  ja v a2s  .  com*/
        ceilingMarker = (Class<Serializable>) Class.forName(ceilingEntity);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    Class<Serializable> securityRoot = rowSecurityService.getFetchRestrictionRoot(
            adminSecurityService.getPersistentAdminUser(), ceilingMarker, filterMappings);
    if (securityRoot != null) {
        ceilingMarker = securityRoot;
    }

    Class<Serializable> ceilingClass = determineRoot(dynamicEntityDao, ceilingMarker, filterMappings);
    CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker);
    Root<Serializable> original = criteria.from(ceilingClass);

    if (isCount) {
        criteria.select(criteriaBuilder.count(original));
    } else if (isMax) {
        criteria.select(criteriaBuilder.max((Path<Number>) ((Object) original.get(maxField))));
    } else {
        criteria.select(original);
    }

    List<Predicate> restrictions = new ArrayList<Predicate>();
    List<Order> sorts = new ArrayList<Order>();
    addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria);

    criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
    if (!isCount && !isMax) {
        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
        //If someone provides a firstResult value, then there is generally pagination going on.
        //In order to produce consistent results, especially with certain databases such as PostgreSQL, 
        //there has to be an "order by" clause.  We'll add one here if we can.
        if (firstResult != null && sorts.isEmpty()) {
            Map<String, Object> idMetaData = dynamicEntityDao.getIdMetadata(ceilingClass);
            if (idMetaData != null) {
                Object idFldName = idMetaData.get("name");
                Object type = idMetaData.get("type");
                if ((idFldName instanceof String) && (type instanceof SingleColumnType)) {
                    criteria.orderBy(criteriaBuilder.asc(original.get((String) idFldName)));
                }
            }
        }
    }
    TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);

    if (!isCount && !isMax) {
        addPaging(response, firstResult, maxResults);
    }

    return response;
}