Java 类javax.persistence.criteria.Order 实例源码

项目:sucok-framework    文件:QueryFormHelper.java   
public static <T> QueryWrapper createQueryWrapper(final BaseQueryForm form) {
    return  (Root<?> root, CriteriaQuery<?> query, CriteriaBuilder cb, boolean sort)-> {
            List<Predicate> predicates = new ArrayList<>();
            addSearch(form, predicates, root, cb);
            addAndFields(form, predicates, root, cb);
            //加入或条件
            addOrFields(form, predicates, root, cb);
            Predicate[] array = new Predicate[predicates.size()];
            predicates.toArray(array);
            query.where(array);
            // 加入排序
            if (sort) {
                List<Order> orders = getOrdes(form, root);
                query.orderBy(orders);
            }

    };
}
项目:sucok-framework    文件:QueryFormHelper.java   
public static <T> Specification<T> createSpecification(final PaginationForm form) {
    return (Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
            List<Predicate> predicates = new ArrayList<>();
            //加入搜索条件
            addSearch(form, predicates, root, cb);

            //加入与条件

            addAndFields(form, predicates, root, cb);
            //加入或条件
            addOrFields(form, predicates, root, cb);
            Predicate[] array = new Predicate[predicates.size()];
            predicates.toArray(array);
            query.where(array);
            // 加入排序
            List<Order> orders = getOrdes(form, root);
            query.orderBy(orders);
            return null;

    };
}
项目:sucok-framework    文件:QueryFormHelper.java   
/**
 * 加入排序依据
 */
private static <T> List<Order> getOrdes(BaseQueryForm form, Root<T> root) {
    String orderBy = form.getOrderMapping();
    if (StringUtils.isEmpty(orderBy)) {
        return Collections.emptyList();
    }
    String[] groups = orderBy.trim().split(",");
    List<Order> orders = new ArrayList<>(groups.length);
    for (String group : groups) {
        boolean ascending = true;
        String[] array = group.split("\\s", 2);
        String field = array[0];
        if (array.length > 1) {
            ascending = "asc".equals(array[1].toLowerCase());
        }
        Order order = new OrderImpl(getPath(root, field), ascending);
        orders.add(order);
    }
    return orders;
}
项目:sucok-framework    文件:QueryFormHelper.java   
public static <T> List<Order> getOrdes(String orderBy, Root<T> root) {
    if (StringUtils.isEmpty(orderBy)) {
        return Collections.emptyList();
    }
    String[] groups = orderBy.trim().split(",");
    List<Order> orders = new ArrayList<Order>(groups.length);
    for (String group : groups) {
        boolean ascending = true;
        String[] array = group.split("\\s", 2);
        String field = array[0];
        if (array.length > 1) {
            ascending = "asc".equals(array[0].toLowerCase());
        }
        Order order = new OrderImpl(getPath(root, field), ascending);
        orders.add(order);
    }
    return orders;
}
项目:osc-core    文件:OSCEntityManager.java   
public List<T> listAll(boolean asc, String... orderby) {
    CriteriaBuilder cb = this.em.getCriteriaBuilder();

    CriteriaQuery<T> query = cb.createQuery(this.clazz);
    Root<T> from = query.from(this.clazz);
    query = query.select(from).distinct(true);

    if (orderby != null) {
        query = query.orderBy(Arrays.stream(orderby)
                .map(f -> from.get(f))
                .map(e -> asc ? cb.asc(e) : cb.desc(e))
                .toArray(i -> new Order[i]));
    }
    List<T> ls = this.em.createQuery(query).getResultList();
    return ls;
}
项目:osc-core    文件:OSCEntityManager.java   
/**
 * Find list of children entities by their parent Id
 *
 * @param parentEntityName
 *            The parent entity name by which id will be queried.
 * @param parentId
 *            Parent entity identifier for which children are queried.
 * @return List of children owned by parent entity
 */
public List<T> findByParentId(String parentEntityName, Long parentId, String... orderby) {

    CriteriaBuilder cb = this.em.getCriteriaBuilder();

    CriteriaQuery<T> query = cb.createQuery(this.clazz);

    Root<T> root = query.from(this.clazz);
    query = query.select(root)
            .distinct(true)
            .where(
            cb.equal(root.join(parentEntityName).get("id"), parentId));

    if (orderby != null) {
        query = query.orderBy(Arrays.stream(orderby)
                .map(f -> cb.asc(root.get(f)))
                .toArray(i -> new Order[i]));
    }

    List<T> list = this.em.createQuery(query).getResultList();

    return list;
}
项目:aws-photosharing-example    文件:ServiceFacade.java   
private <T> List<Order> getSort(Root<T> p_root, CriteriaBuilder p_builder, Sort[] p_sort) {

    List<Order> order = new LinkedList<Order>();

    if (p_sort != null && p_sort.length > 0) {              

        for (Sort sort : p_sort) {
            Path<?> property_path = null;       

            for (String hop : sort.getPropertyPath()) {
                if (property_path == null)
                    property_path = p_root.get(hop);
                else
                    property_path = property_path.get(hop);
            }
            if (sort.getOrderAscending()) {
                order.add(p_builder.asc(property_path));
            } else {
                order.add(p_builder.desc(property_path));
            }
        }           
    }

    return order;
}
项目:Pedidex    文件:JpaCriteriaHelper.java   
/**
 * Obtem lista com os resultados
 * @return Lista de resultados
 */
public List<T> getResults() {
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
    Root<T> root                   = criteriaQuery.from(entityClass);
    setupQuery(criteriaQuery, root);

    // ORDER BY
    if ( ! orders.isEmpty() ) {
        ArrayList<Order> jpaOrders = new ArrayList<>();
        for (OrderEntry orderField : orders) {
            if ( orderField.order.equals(OrderDirection.ASC) ) {
                jpaOrders.add( criteriaBuilder.asc(getPath(orderField.fieldNames, root)));
            } else {
                jpaOrders.add( criteriaBuilder.desc(getPath(orderField.fieldNames, root)));
            }
        }
        criteriaQuery.orderBy( jpaOrders );
    }

    if ( pageNumber != null ) {
        return em.createQuery(criteriaQuery).setFirstResult( (pageNumber - 1) * pageSize ).setMaxResults(pageSize)
                        .getResultList();
    } else {
        return em.createQuery(criteriaQuery).getResultList();
    }
}
项目:datatable-java    文件:DatatableHelper.java   
/**
 * Creates a 'LIMIT .. OFFSET .. ORDER BY ..' clause for the given {@link DatatableQuery}.
 * 
 * @param input
 *            the {@link DatatableQuery} mapped from the Ajax request
 * @return a {@link Pageable}, must not be {@literal null}.
 */
static <T> Pageable getPageable(final DatatableQuery<?, T> input) {
    final List<org.andresoviedo.datatable.Sort.Order> orders =
        new ArrayList<org.andresoviedo.datatable.Sort.Order>();
    for (final DatatableOrder order : input.getOrder()) {
        final DatatableColumn column = input.getColumns().get(order.getColumn());
        if (column.getOrderable()) {
            final String sortColumn = column.getData();
            final Direction sortDirection = Direction.fromString(order.getDir());
            orders.add(new org.andresoviedo.datatable.Sort.Order(sortDirection, sortColumn));
        }
    }
    org.andresoviedo.datatable.Sort sort = null;
    if (!orders.isEmpty()) {
        sort = new org.andresoviedo.datatable.Sort(orders);
    }

    if (input.getLength() == -1) {
        input.setStart(0);
        input.setLength(Integer.MAX_VALUE);
    }
    return new DataTablePage(input.getStart(), input.getLength(), sort);
}
项目:darceo    文件:GenericQuerySorterBuilderImpl.java   
/**
 * Adds sorting by given parameter and order type (ascending or descending).
 * 
 * @param parameter
 *            parameter by which sorting will be performed
 * @param ascendingly
 *            defines whether (<code>true</code>) or not (<code>false</code>)sorting will be ascending
 */
protected void addOrdering(Expression<?> parameter, boolean ascendingly) {
    ensureInitializedOrders();
    Order order = getExistingOrderExpression(parameter);
    if (order != null) {
        boolean orderingDiffers = order.isAscending() ^ ascendingly;
        if (orderingDiffers) {
            order.reverse();
            return;
        }
    } else {
        if (ascendingly) {
            orders.add(criteriaBuilder.asc(parameter));
        } else {
            orders.add(criteriaBuilder.desc(parameter));
        }
    }
}
项目:owsi-core-parent    文件:JpaDaoSupport.java   
/**
 * @deprecated Utiliser QueryDSL
 */
@Deprecated
protected <T> List<T> listEntity(Class<T> objectClass, Expression<Boolean> filter, Integer limit, Integer offset, Order... orders) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(objectClass);
    rootCriteriaQuery(builder, criteria, objectClass);

    if (filter != null) {
        filterCriteriaQuery(criteria, filter);
    }
    if (orders != null && orders.length > 0) {
        criteria.orderBy(orders);
    }
    TypedQuery<T> query = buildTypedQuery(criteria, limit, offset);

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

    if (orders == null || orders.length == 0) {
        sort(entities);
    }

    return entities;
}
项目:herd    文件:UserNamespaceAuthorizationDaoImpl.java   
@Override
public List<UserNamespaceAuthorizationEntity> getUserNamespaceAuthorizationsByNamespace(String namespace)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<UserNamespaceAuthorizationEntity> criteria = builder.createQuery(UserNamespaceAuthorizationEntity.class);

    // The criteria root is the user namespace authorization.
    Root<UserNamespaceAuthorizationEntity> userNamespaceAuthorizationEntity = criteria.from(UserNamespaceAuthorizationEntity.class);

    // Join to the other tables we can filter on.
    Join<UserNamespaceAuthorizationEntity, NamespaceEntity> namespaceEntity =
        userNamespaceAuthorizationEntity.join(UserNamespaceAuthorizationEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespace.toUpperCase());

    // Order by user id.
    Order orderBy = builder.asc(userNamespaceAuthorizationEntity.get(UserNamespaceAuthorizationEntity_.userId));

    // Add all clauses for the query.
    criteria.select(userNamespaceAuthorizationEntity).where(queryRestriction).orderBy(orderBy);

    // Execute the query and return the result list.
    return entityManager.createQuery(criteria).getResultList();
}
项目:herd    文件:TagTypeDaoImpl.java   
@Override
public List<TagTypeEntity> getTagTypes()
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagTypeEntity> criteria = builder.createQuery(TagTypeEntity.class);

    // The criteria root is the tag type entity.
    Root<TagTypeEntity> tagTypeEntityRoot = criteria.from(TagTypeEntity.class);

    // Get the columns.
    Path<String> displayNameColumn = tagTypeEntityRoot.get(TagTypeEntity_.displayName);
    Path<Integer> tagTypeOrderColumn = tagTypeEntityRoot.get(TagTypeEntity_.orderNumber);

    // Order the results by tag type's order and display name.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(tagTypeOrderColumn));
    orderBy.add(builder.asc(displayNameColumn));

    // Add all clauses to the query.
    criteria.select(tagTypeEntityRoot).orderBy(orderBy);

    // Run the query and return the results.
    return entityManager.createQuery(criteria).getResultList();
}
项目:judgels-jophiel    文件:UserEmailHibernateDao.java   
@Override
public List<String> sortUserJidsByEmail(Collection<String> userJids, String sortBy, String order) {
    CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
    CriteriaQuery<String> query = cb.createQuery(String.class);
    Root<UserEmailModel> root = query.from(UserEmailModel.class);

    Predicate condition = root.get(UserEmailModel_.userJid).in(userJids);

    Order orderBy = null;
    if ("asc".equals(order)) {
        orderBy = cb.asc(root.get(sortBy));
    } else {
        orderBy = cb.desc(root.get(sortBy));
    }

    query.select(root.get(UserEmailModel_.userJid)).where(condition).orderBy(orderBy);
    return JPA.em().createQuery(query).getResultList();
}
项目:judgels-jophiel    文件:UserHibernateDao.java   
@Override
public List<String> sortUserJidsByUserAttribute(Collection<String> userJids, String sortBy, String order) {
    CriteriaBuilder cb = JPA.em().getCriteriaBuilder();
    CriteriaQuery<String> query = cb.createQuery(String.class);
    Root<UserModel> root = query.from(UserModel.class);

    Predicate condition = root.get(UserModel_.jid).in(userJids);

    Order orderBy = null;
    if ("asc".equals(order)) {
        orderBy = cb.asc(root.get(sortBy));
    } else {
        orderBy = cb.desc(root.get(sortBy));
    }

    query.select(root.get(UserModel_.jid)).where(condition).orderBy(orderBy);
    return JPA.em().createQuery(query).getResultList();
}
项目:blcdemo    文件:StaticAssetDaoImpl.java   
public List<StaticAsset> readAllStaticAssets() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<StaticAsset> criteria = builder.createQuery(StaticAsset.class);
    Root<StaticAssetImpl> handler = criteria.from(StaticAssetImpl.class);
    criteria.select(handler);
    List<Predicate> restrictions = new ArrayList<Predicate>();
    List<Order> sorts = new ArrayList<Order>();
    try {
        if (queryExtensionManager != null) {
            queryExtensionManager.getProxy().setup(StaticAssetImpl.class, null);
            queryExtensionManager.getProxy().refineRetrieve(StaticAssetImpl.class, null, builder, criteria, handler, restrictions);
            queryExtensionManager.getProxy().refineOrder(StaticAssetImpl.class, null, builder, criteria, handler, sorts);
        }
        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
        return em.createQuery(criteria).getResultList();
    } catch (NoResultException e) {
        return new ArrayList<StaticAsset>();
    }
}
项目:karaku    文件:SearchParamJPAHelper.java   
public CriteriaQuery<T> apply(SearchParam params, CriteriaQuery<T> query,
        Root<T> root, CriteriaBuilder builder) {

    if (params == null) {
        return query;
    }
    List<Order> orders = new ArrayList<Order>();
    if (params.getOrders() != null) {
        for (OrderParam orderParam : params.getOrders()) {
            if (orderParam.isAsc()) {
                orders.add(builder.asc(root.get(orderParam.getColumnName())));
            } else {
                orders.add(builder.desc(root.get(orderParam.getColumnName())));
            }
        }
    }
    query.orderBy(orders);
    return query;
}
项目:ineform    文件:ModuleQuery.java   
@Override
public Order getOrderExpression(AbstractSearch action, CriteriaBuilder cb, Root<Module> from) {
    Order o;
    String orderKey = action == null ? null : action.getOrderKey();
    if (orderKey == null) {
        // default default order
        orderKey = IFConsts.KEY_ID;
        // default order specified:
    }
    Expression<?> orderExpr = null;
    List<String> idList = SharedUtil.listFromDotSeparated(orderKey);

    {
        orderExpr = from.get(orderKey);
    }
    if (action.isDescending() == null)
        // default order
        o = cb.asc(orderExpr);
    else if (action.isDescending())
        o = cb.desc(orderExpr);
    else
        o = cb.asc(orderExpr);
    return o;
}
项目:ineform    文件:LangQuery.java   
@Override
public Order getOrderExpression(AbstractSearch action, CriteriaBuilder cb, Root<Lang> from) {
    Order o;
    String orderKey = action == null ? null : action.getOrderKey();
    if (orderKey == null) {
        // default default order
        orderKey = IFConsts.KEY_ID;
        // default order specified:
    }
    Expression<?> orderExpr = null;
    List<String> idList = SharedUtil.listFromDotSeparated(orderKey);

    {
        orderExpr = from.get(orderKey);
    }
    if (action.isDescending() == null)
        // default order
        o = cb.asc(orderExpr);
    else if (action.isDescending())
        o = cb.desc(orderExpr);
    else
        o = cb.asc(orderExpr);
    return o;
}
项目:ineform    文件:UserQuery.java   
@Override
public Order getOrderExpression(AbstractSearch action, CriteriaBuilder cb, Root<User> from) {
    Order o;
    String orderKey = action == null ? null : action.getOrderKey();
    if (orderKey == null) {
        // default default order
        orderKey = IFConsts.KEY_ID;
        // default order specified:
    }
    Expression<?> orderExpr = null;
    List<String> idList = SharedUtil.listFromDotSeparated(orderKey);
    ;

    {
        orderExpr = from.get(orderKey);
    }
    if (action.isDescending() == null)
        // default order
        o = cb.asc(orderExpr);
    else if (action.isDescending())
        o = cb.desc(orderExpr);
    else
        o = cb.asc(orderExpr);
    return o;
}
项目:ineform    文件:CompanyQuery.java   
@Override
public Order getOrderExpression(AbstractSearch action, CriteriaBuilder cb, Root<Company> from) {
    Order o;
    String orderKey = action == null ? null : action.getOrderKey();
    if (orderKey == null) {
        // default default order
        orderKey = IFConsts.KEY_ID;
        // default order specified:
    }
    Expression<?> orderExpr = null;
    List<String> idList = SharedUtil.listFromDotSeparated(orderKey);

    {
        orderExpr = from.get(orderKey);
    }
    if (action.isDescending() == null)
        // default order
        o = cb.asc(orderExpr);
    else if (action.isDescending())
        o = cb.desc(orderExpr);
    else
        o = cb.asc(orderExpr);
    return o;
}
项目:ineform    文件:UserQuery.java   
@Override
public Order getOrderExpression(AbstractSearch action, CriteriaBuilder cb, Root<User> from) {
    Order o;
    String orderKey = action == null ? null : action.getOrderKey();
    if (orderKey == null) {
        // default default order
        orderKey = IFConsts.KEY_ID;
        // default order specified:
    }
    Expression<?> orderExpr = null;
    List<String> idList = SharedUtil.listFromDotSeparated(orderKey);

    {
        orderExpr = from.get(orderKey);
    }
    if (action.isDescending() == null)
        // default order
        o = cb.asc(orderExpr);
    else if (action.isDescending())
        o = cb.desc(orderExpr);
    else
        o = cb.asc(orderExpr);
    return o;
}
项目:VaadinUtils    文件:JpaBaseDao.java   
/**
 * Returns all rows ordered by the given set of entity attribues.
 *
 * You may pass in an array of attributes and a order by clause will be
 * added for each attribute in turn e.g. order by order[0], order[1] ....
 */
@Override
public List<E> findAll(SingularAttribute<E, ?> order[])
{
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();

    CriteriaQuery<E> criteria = builder.createQuery(entityClass);

    Root<E> root = criteria.from(entityClass);
    criteria.select(root);
    if (order != null)
    {
        List<Order> ordering = new LinkedList<>();
        for (SingularAttribute<E, ?> field : order)
        {
            ordering.add(builder.asc(root.get(field)));

        }
        criteria.orderBy(ordering);
    }
    List<E> results = getEntityManager().createQuery(criteria).getResultList();

    return results;

}
项目:activejpa    文件:Filter.java   
/**
 * Constructs the select criteria query
 * 
 * @param builder
 * @param query
 * @param root
 */
public <T extends Model> void constructQuery(CriteriaBuilder builder, CriteriaQuery<?> query, Root<T> root) {
    if (conditions != null || !conditions.isEmpty()) {
        List<Predicate> predicates = new ArrayList<Predicate>();
        for (Condition condition : conditions) {
            predicates.add(condition.constructQuery(builder, root));
        }
        query.where(predicates.toArray(new Predicate[0]));
    }

    if (sortFields != null && !sortFields.isEmpty()) {
        List<Order> orders = new ArrayList<Order>();
        for (SortField sortField : sortFields) {
            orders.add(sortField.getOrder(builder, root));
        }
        query.orderBy(orders);
    }
}
项目:jdal    文件:JpaDao.java   
/**
 * Gets a NamedQuery from page, setup order, params and page result count.
 * @param page request page
 * @return a TypedQuery from a NamedQuery
 */
@SuppressWarnings("unchecked")
protected <K> TypedQuery<K> getNamedQuery(Page<K> page) {
    Filter filter = null;
    TypedQuery<K> query = null;

    if (page.getFilter() instanceof Filter) {
        filter = (Filter) page.getFilter();
        String queryString = getQueryString(filter.getFilterName());
        if (queryString != null) {
            String countQueryString = JpaUtils.createCountQueryString(queryString);
            TypedQuery<Long> countQuery =  em.createQuery(countQueryString, Long.class);
            applyFilter(countQuery, filter);
            page.setCount(countQuery.getSingleResult().intValue());
            // add Order
            if (page.getSortName() != null)
                queryString = JpaUtils.addOrder(queryString, page.getSortName(),
                    page.getOrder() == Page.Order.ASC);

            query = (TypedQuery<K>) em.createQuery(queryString);
            applyFilter(query, filter);
        }
    }

    return query;
}
项目:RemInD    文件:CriteriaQueryParameterHolder.java   
public TypedQuery<E> createSelectCriteriaQuery(EntityManager entityManager)
{
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(getClazz());
    Root<E> root = criteriaQuery.from(getClazz());

    Expression<Boolean> filterCriteria = createFilterCriteria(criteriaBuilder, root);
    if (filterCriteria != null)
    {
        criteriaQuery.where(filterCriteria);
    }

    List<Order> orderList = createOrderList(criteriaBuilder, root);
    if (!orderList.isEmpty())
    {
        criteriaQuery.orderBy(orderList);
    }

    return setLimits(entityManager.createQuery(criteriaQuery));
}
项目:RemInD    文件:CriteriaQueryParameterHolder.java   
private List<Order> createOrderList(CriteriaBuilder criteriaBuilder, Root<E> root)
{
    List<Order> orderList = new ArrayList<Order>();

    Order order;
    for (String parameterName : getOrderedParameterListReference())
    {
        order = getParameter(parameterName).createOrder(root, criteriaBuilder);
        if (order != null)
        {
            orderList.add(order);
        }
    }

    // TODO: review and find more general solution without hard-coded id
    // Such ordering is needed for pagination as it is not garanteed that database returns data always in the
    // same order.
    orderList.add(criteriaBuilder.asc(root.get("id")));

    return orderList;
}
项目:deltaspike    文件:OrderBy.java   
@Override
public <R> void process(CriteriaQuery<R> query, CriteriaBuilder builder, Path<P> path)
{
    List<Order> orders = new ArrayList<Order>();
    Iterator<OrderByDefinition<?>> iterator = orderByDefinitions.iterator();
    while (iterator.hasNext())
    {
        OrderByDefinition<?> orderByDefinition = iterator.next();
        switch (orderByDefinition.getDir())
        {
            case ASC:
                orders.add(builder.asc(path.get(orderByDefinition.getAtt())));
                break;
            default:
                orders.add(builder.desc(path.get(orderByDefinition.getAtt())));
        }
    }
    query.orderBy(orders);
}
项目:sucok-framework    文件:BaseDao.java   
public List<T> findByProperty(String name, Object value, String orderBy) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<T> query = cb.createQuery(entityClass);
    Root<T> root = query.from(entityClass);
    query.where(cb.equal(QueryFormHelper.getPath(root, name), value));
    if (!StringUtils.isEmpty(orderBy)) {
        List<Order> orders = QueryFormHelper.getOrdes(orderBy, root);
        query.orderBy(orders);
    }
    TypedQuery<T> typedQuery = em.createQuery(query);
    return typedQuery.getResultList();
}
项目:datatable-java    文件:DatatableHelper.java   
static <T> List<Order> getOrderBy(final Root<T> from, final CriteriaBuilder qb, final Pageable pageable) {
    final List<Order> orderBy = new ArrayList<Order>();
    for (final Iterator<Sort.Order> it = pageable.getSort().iterator(); it.hasNext();) {
        final org.andresoviedo.datatable.Sort.Order order = it.next();
        final Path<?> entityProperty = DatatableHelper.getExpression(from, order.getProperty(), null);
        if (order.isAscending()) {
            orderBy.add(qb.asc(entityProperty));
        } else {
            orderBy.add(qb.desc(entityProperty));
        }
    }
    return orderBy;
}
项目:webpedidos    文件:Produtos.java   
public List<Produto> filtrados(ProdutoFilter filter) {

        Metamodel meta = manager.getMetamodel();
        EntityType<Produto> type = meta.entity(Produto.class);

        CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
        CriteriaQuery<Produto> criteriaQuery = criteriaBuilder.createQuery(Produto.class);
        Root<Produto> root = criteriaQuery.from(Produto.class);

        if (StringUtils.isNotBlank(filter.getSku())) {
            Predicate equalsPredicate = criteriaBuilder.equal(root.get("sku"), filter.getSku());
            criteriaQuery.where(equalsPredicate);
        }

        // vamos usar o atributo nome para filtragem e ordenação
        Path<String> nomeAttr = root.get(type.getDeclaredSingularAttribute("nome", String.class));

        if (StringUtils.isNotBlank(filter.getNome())) {
            Expression<String> expr = criteriaBuilder.lower(nomeAttr);

            // where nome like '%nome%'
            String match = String.format("%%%s%%", filter.getNome().toLowerCase());

            Predicate likePredicate = criteriaBuilder.like(expr, match);
            criteriaQuery.where(likePredicate);
        }

        Order ordernacao = criteriaBuilder.asc(nomeAttr);

        criteriaQuery.orderBy(ordernacao);

        return manager.createQuery(criteriaQuery).getResultList();
    }
项目:rpb    文件:JpaUtil.java   
public static <E> List<Order> buildJpaOrders(Iterable<OrderBy> orders, Root<E> root, CriteriaBuilder builder, SearchParameters sp) {
    List<Order> jpaOrders = newArrayList();

    for (OrderBy ob : orders) {
        Path<?> path = getPropertyOrderPath(root, ob.getProperty(), sp);

        if (ob.isOrderDesc()) {
            jpaOrders.add(builder.desc(path));
        } else {
            jpaOrders.add(builder.asc(path));
        }
    }
    return jpaOrders;
}
项目:katharsis-framework    文件:JpaCriteriaQueryBackend.java   
@Override
public Order newSort(Expression<?> expr, Direction dir) {
    if (dir == Direction.ASC) {
        return cb.asc(expr);
    }
    else {
        return cb.desc(expr);
    }
}
项目:katharsis-framework    文件:JpaCriteriaQueryExecutorImpl.java   
@Override
@SuppressWarnings({ "rawtypes" })
public long getTotalRowCount() {
    Selection<T> selection = query.getSelection();
    List<Order> orderList = query.getOrderList();
    try {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        Expression<Long> countExpr;

        Set<Root<?>> roots = query.getRoots();
        if (roots.size() != 1) {
            throw new IllegalStateException("cannot compute totalRowCount in case of multiple query roots");
        }
        if (!query.getGroupList().isEmpty()) {
            throw new IllegalStateException("cannot compute totalRowCount for grouped queries");
        }

        // transform query to a count query
        Root root = roots.iterator().next();
        countExpr = builder.count(root);
        query.multiselect(countExpr);
        query.orderBy(new ArrayList<Order>());
        TypedQuery countQuery = em.createQuery(query);

        return (Long) countQuery.getSingleResult();
    }
    finally {
        // transform count query back to regular query
        query.multiselect(selection);
        query.orderBy(orderList);
    }
}
项目:lider    文件:PluginDbServiceImpl.java   
@Override
public <T> List<T> findByProperties(Class<T> entityClass, Map<String, Object> propertiesMap,
        List<PropertyOrder> orders, Integer maxResults) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(entityClass);
    Root<T> from = criteria.from(entityClass);
    criteria.select(from);
    Predicate predicate = null;

    if (propertiesMap != null) {
        for (Entry<String, Object> entry : propertiesMap.entrySet()) {
            if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
                Predicate pred = builder.equal(from.get(entry.getKey()), entry.getValue());
                predicate = predicate == null ? pred : builder.and(predicate, pred);
            }
        }
        if (predicate != null) {
            criteria.where(predicate);
        }
    }

    if (orders != null && !orders.isEmpty()) {
        List<Order> orderList = new ArrayList<Order>();
        for (PropertyOrder order : orders) {
            orderList.add(order.getOrderType() == OrderType.ASC ? builder.asc(from.get(order.getPropertyName()))
                    : builder.desc(from.get(order.getPropertyName())));
        }
        criteria.orderBy(orderList);
    }

    TypedQuery<T> query = entityManager.createQuery(criteria);
    if (maxResults != null) {
        query = query.setMaxResults(maxResults);
    }

    List<T> list = query.getResultList();
    logger.debug("Objects found: {}", list);
    return list;
}
项目:jpasecurity    文件:CriteriaVisitor.java   
/**
 * {@inheritDoc}
 */
public boolean visit(JpqlOrderBy node, CriteriaHolder query) {
    List<Order> orders = new ArrayList<Order>();
    for (int i = 0; i < node.jjtGetNumChildren(); i++) {
        node.jjtGetChild(i).visit(this, query);
        orders.add(query.<Order>getCurrentValue());
    }
    query.getCriteria().orderBy(orders);
    return false;
}
项目:ibankapp-base    文件:QueryUtils.java   
/**
 * 根据排序规则获取Jpa Order对象集合.
 *
 * @param sort 排序规则对象
 * @param root 实体类ROOT
 * @param cb 查询构建器
 * @return Jpa Order对象集合
 */
public static List<Order> toOrders(Sort sort, Root<?> root, CriteriaBuilder cb) {

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

  if (sort == null) {
    return orders;
  }

  for (Sort.Order order : sort) {
    orders.add(toJpaOrder(order, root, cb));
  }

  return orders;
}
项目:metaworks_framework    文件:RowLevelSecurityServiceImpl.java   
@Override
public void addFetchRestrictions(AdminUser currentUser, String ceilingEntity, List<Predicate> restrictions, List<Order> sorts,
        Root entityRoot,
        CriteriaQuery criteria,
        CriteriaBuilder criteriaBuilder) {
    for (RowLevelSecurityProvider provider : getProviders()) {
        provider.addFetchRestrictions(currentUser, ceilingEntity, restrictions, sorts, entityRoot, criteria, criteriaBuilder);
    }
}
项目:metaworks_framework    文件:CriteriaTranslatorImpl.java   
protected void addSorting(CriteriaBuilder criteriaBuilder, List<Order> sorts, FilterMapping filterMapping, Path path) {
    Expression exp = path;
    if (filterMapping.getNullsLast() != null && filterMapping.getNullsLast()) {
        Object largeValue = getAppropriateLargeSortingValue(path.getJavaType());
        if (largeValue != null) {
            exp = criteriaBuilder.coalesce(path, largeValue);
        }
    }
    if (SortDirection.ASCENDING == filterMapping.getSortDirection()) {
        sorts.add(criteriaBuilder.asc(exp));
    } else {
        sorts.add(criteriaBuilder.desc(exp));
    }
}
项目:metaworks_framework    文件:ProductDaoImpl.java   
protected void attachOrderBy(ProductSearchCriteria 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;
                    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()]));
    }
}