Example usage for javax.persistence.criteria CriteriaQuery orderBy

List of usage examples for javax.persistence.criteria CriteriaQuery orderBy

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaQuery orderBy.

Prototype

CriteriaQuery<T> orderBy(List<Order> o);

Source Link

Document

Specify the ordering expressions that are used to order the query results.

Usage

From source file:gov.guilin.dao.impl.ProductDaoImpl.java

public List<Object[]> findSalesList(Date beginDate, Date endDate, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
    Root<Product> product = criteriaQuery.from(Product.class);
    Join<Product, OrderItem> orderItems = product.join("orderItems");
    Join<Product, gov.guilin.entity.Order> order = orderItems.join("order");
    criteriaQuery.multiselect(product.get("id"), product.get("sn"), product.get("name"),
            product.get("fullName"), product.get("price"),
            criteriaBuilder.sum(orderItems.<Integer>get("quantity")), criteriaBuilder.sum(criteriaBuilder
                    .prod(orderItems.<Integer>get("quantity"), orderItems.<BigDecimal>get("price"))));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(order.<Date>get("createDate"), beginDate));
    }// w w  w .  j a va2 s  . co  m
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(order.<Date>get("createDate"), endDate));
    }
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(order.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.equal(order.get("paymentStatus"), PaymentStatus.paid));
    criteriaQuery.where(restrictions);
    criteriaQuery.groupBy(product.get("id"), product.get("sn"), product.get("name"), product.get("fullName"),
            product.get("price"));
    criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(
            criteriaBuilder.prod(orderItems.<Integer>get("quantity"), orderItems.<BigDecimal>get("price")))));
    TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (count != null && count >= 0) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TAzCarinfoEntity> listAllCandidateCars(String[] applicationIds, String keyword, Integer offset,
        Integer limit, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TAzCarinfoEntity> cq = cb.createQuery(TAzCarinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    carRoot.fetch(TAzCarinfoEntity_.driver, JoinType.LEFT);

    cq.select(carRoot);//w  w w  .  j  a  v  a 2 s  .c  o  m
    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, null, cb,
            principalExt);
    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.clzt), "02"),
            cb.or(cb.equal(carRoot.get(TAzCarinfoEntity_.repairingState), RepairingState.NONE.id()),
                    cb.isNull(carRoot.get(TAzCarinfoEntity_.repairingState))

            ), cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(carRoot.get(TAzCarinfoEntity_.sysOrg).get(TSysOrgEntity_.orgname),
                        "%" + keyword + "%"),
                        cb.like(carRoot.get(TAzCarinfoEntity_.cphm), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb.asc(carRoot.get(TAzCarinfoEntity_.cphm)));
    TypedQuery<TAzCarinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("cars", principalExt);

    return query.getResultList();
}

From source file:com.creditcloud.common.entities.dao.AbstractReadDAO.java

/**
 * list entity by CriteriaInfo/*w w w.ja  va 2s  . com*/
 *
 * @param criteriaInfo
 * @return PagedResult
 */
public PagedResult<T> list(CriteriaInfo criteriaInfo) {
    EntityManager em = getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(entityClass);
    Root<T> userRoot = cq.from(entityClass);
    cq.select(userRoot);
    ParamInfo paramInfo = criteriaInfo.getParamInfo();
    PageInfo pageInfo = criteriaInfo.getPageInfo();
    SortInfo sortInfo = criteriaInfo.getSortInfo();

    //build query for paramInfo
    if (paramInfo != null) {
        Set<Predicate> andCriteria = new HashSet();
        Set<Predicate> orCriteria = new HashSet();

        for (ParamItem item : paramInfo.getParamItems()) {
            Predicate predicate;
            if (item.getValue() instanceof String) {
                //fuzy search for string
                String regExp = "%" + item.getValue() + "%";
                predicate = cb.like((Expression) (userRoot.get(item.getFieldName())), regExp);
            } else {
                predicate = cb.equal((userRoot.get(item.getFieldName())), item.getValue());
            }

            switch (item.getOperator()) {
            case AND:
                andCriteria.add(predicate);
                break;
            case OR:
                orCriteria.add(predicate);
                break;
            }
        }
        if (orCriteria.size() > 0) {
            Predicate or = cb.or(orCriteria.toArray(new Predicate[orCriteria.size()]));
            andCriteria.add(or);
        }
        if (andCriteria.size() > 0) {
            Predicate and = cb.and(andCriteria.toArray(new Predicate[andCriteria.size()]));
            cq.where(and);
        }
    }

    //build query for sortInfo
    Set<Order> orderPredicate = new HashSet<>();
    if (sortInfo != null) {
        for (SortItem item : sortInfo.getSortItems()) {
            if (item.isDescending()) {
                orderPredicate.add(cb.desc(userRoot.get(item.getFieldName())));
            } else {
                orderPredicate.add(cb.asc(userRoot.get(item.getFieldName())));
            }
        }
    }
    if (orderPredicate.size() > 0) {
        cq.orderBy(orderPredicate.toArray(new Order[orderPredicate.size()]));
    }

    TypedQuery<T> query = em.createQuery(cq);
    //set result range
    if (pageInfo != null) {
        query.setFirstResult(pageInfo.getOffset());
        query.setMaxResults(pageInfo.getSize());
    }

    int totalSize;
    if (paramInfo != null && paramInfo.getParamItems().size() > 0) {
        totalSize = count(paramInfo);
    } else {
        totalSize = count();
    }

    return new PagedResult(query.getResultList(), totalSize);
}

From source file:org.openmeetings.app.data.user.Usermanagement.java

/**
 * suche eines Bentzers/*from  w ww  . ja  va2  s . c o  m*/
 * 
 * @param user_level
 * @param searchstring
 * @param max
 * @param start
 * @return
 */
public List<Users> searchUser(long user_level, String searchcriteria, String searchstring, int max, int start,
        String orderby, boolean asc) {
    if (authLevelManagement.checkAdminLevel(user_level)) {
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Users> cq = cb.createQuery(Users.class);
            Root<Users> c = cq.from(Users.class);
            Expression<String> literal = cb.literal("%" + searchstring + "%");
            // crit.add(Restrictions.ilike(searchcriteria, "%" +
            // 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<Users> q = em.createQuery(cq);
            q.setFirstResult(start);
            q.setMaxResults(max);
            List<Users> contactsZ = q.getResultList();
            return contactsZ;
        } catch (Exception ex2) {
            log.error("searchUser", ex2);
        }
    }
    return null;
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword,
        Integer offset, Integer limit, PrincipalExt principalExt) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class);
    Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    cq.select(driverRoot);//  w  w  w .jav  a  2s .c o m

    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb,
            principalExt);

    Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class);
    Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class);
    subqueryLicense.select(driverRoot);
    subqueryLicense.where(

            cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)),
            cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq),
                    driverRoot.get(TRsDriverinfoEntity_.drivecartype)));

    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"),
            cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype))

            ),

            cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb
            .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername))

    )));
    TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    return query.getResultList();

}

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

/**
 * Sets the criteria parameters for searching execution.
 *
 * @param entity//ww  w .j  a  v a 2  s.  co  m
 *            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;
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void processSort(final SearchParameterMap theParams) {

    // Set<Long> loadPids = theLoadPids;
    if (theParams.getSort() != null && isNotBlank(theParams.getSort().getParamName())) {
        List<Order> orders = new ArrayList<Order>();
        List<Predicate> predicates = new ArrayList<Predicate>();
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<ResourceTable> from = cq.from(ResourceTable.class);

        createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));

        createSort(builder, from, theParams.getSort(), orders, predicates);

        if (orders.size() > 0) {

            // TODO: why do we need the existing list for this join to work?
            Collection<Long> originalPids = doGetPids();

            LinkedHashSet<Long> loadPids = new LinkedHashSet<Long>();
            cq.multiselect(from.get("myId").as(Long.class));
            cq.where(toArray(predicates));
            cq.orderBy(orders);

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);

            for (Tuple next : query.getResultList()) {
                loadPids.add(next.get(0, Long.class));
            }/*w  w  w .  j a va 2 s.co m*/

            ourLog.debug("Sort PID order is now: {}", loadPids);

            ArrayList<Long> pids = new ArrayList<Long>(loadPids);

            // Any ressources which weren't matched by the sort get added to the bottom
            for (Long next : originalPids) {
                if (loadPids.contains(next) == false) {
                    pids.add(next);
                }
            }

            doSetPids(pids);
        }
    }

}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

@Override
public IBundleProvider search(final SearchParameterMap theParams) {
    StopWatch w = new StopWatch();
    final InstantDt now = InstantDt.withCurrentTime();

    Set<Long> loadPids;
    if (theParams.isEmpty()) {
        loadPids = new HashSet<Long>();
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<ResourceTable> from = cq.from(ResourceTable.class);
        cq.multiselect(from.get("myId").as(Long.class));
        Predicate typeEquals = builder.equal(from.get("myResourceType"), myResourceName);
        Predicate notDeleted = builder.isNull(from.get("myDeleted"));
        cq.where(builder.and(typeEquals, notDeleted));

        TypedQuery<Tuple> query = myEntityManager.createQuery(cq);
        for (Tuple next : query.getResultList()) {
            loadPids.add(next.get(0, Long.class));
        }/*from  www . ja  v  a  2s  . c o m*/
    } else {
        loadPids = searchForIdsWithAndOr(theParams);
        if (loadPids.isEmpty()) {
            return new SimpleBundleProvider();
        }
    }

    final List<Long> pids;

    // Handle sorting if any was provided
    if (theParams.getSort() != null && isNotBlank(theParams.getSort().getParamName())) {
        List<Order> orders = new ArrayList<Order>();
        List<Predicate> predicates = new ArrayList<Predicate>();
        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        CriteriaQuery<Tuple> cq = builder.createTupleQuery();
        Root<ResourceTable> from = cq.from(ResourceTable.class);
        predicates.add(from.get("myId").in(loadPids));
        createSort(builder, from, theParams.getSort(), orders, predicates);
        if (orders.size() > 0) {
            Set<Long> originalPids = loadPids;
            loadPids = new LinkedHashSet<Long>();
            cq.multiselect(from.get("myId").as(Long.class));
            cq.where(predicates.toArray(new Predicate[0]));
            cq.orderBy(orders);

            TypedQuery<Tuple> query = myEntityManager.createQuery(cq);

            for (Tuple next : query.getResultList()) {
                loadPids.add(next.get(0, Long.class));
            }

            ourLog.info("Sort PID order is now: {}", loadPids);

            pids = new ArrayList<Long>(loadPids);

            // Any ressources which weren't matched by the sort get added to the bottom
            for (Long next : originalPids) {
                if (loadPids.contains(next) == false) {
                    pids.add(next);
                }
            }

        } else {
            pids = new ArrayList<Long>(loadPids);
        }
    } else {
        pids = new ArrayList<Long>(loadPids);
    }

    // Load _revinclude resources
    if (theParams.getRevIncludes() != null && theParams.getRevIncludes().isEmpty() == false) {
        loadReverseIncludes(pids, theParams.getRevIncludes());
    }

    IBundleProvider retVal = new IBundleProvider() {
        @Override
        public InstantDt getPublished() {
            return now;
        }

        @Override
        public List<IResource> getResources(final int theFromIndex, final int theToIndex) {
            TransactionTemplate template = new TransactionTemplate(myPlatformTransactionManager);
            return template.execute(new TransactionCallback<List<IResource>>() {
                @Override
                public List<IResource> doInTransaction(TransactionStatus theStatus) {
                    List<Long> pidsSubList = pids.subList(theFromIndex, theToIndex);

                    // Execute the query and make sure we return distinct results
                    List<IResource> retVal = new ArrayList<IResource>();
                    loadResourcesByPid(pidsSubList, retVal, BundleEntrySearchModeEnum.MATCH);

                    /*
                     * Load _include resources - Note that _revincludes are handled differently
                     * than _include ones, as they are counted towards the total count and paged,
                     * so they are loaded outside the bundle provider
                     */
                    if (theParams.getIncludes() != null && theParams.getIncludes().isEmpty() == false) {
                        Set<IdDt> previouslyLoadedPids = new HashSet<IdDt>();
                        for (IResource next : retVal) {
                            previouslyLoadedPids.add(next.getId().toUnqualifiedVersionless());
                        }

                        Set<IdDt> includePids = new HashSet<IdDt>();
                        List<IResource> resources = retVal;
                        do {
                            includePids.clear();

                            FhirTerser t = getContext().newTerser();
                            for (Include next : theParams.getIncludes()) {
                                for (IResource nextResource : resources) {
                                    RuntimeResourceDefinition def = getContext()
                                            .getResourceDefinition(nextResource);
                                    List<Object> values = getIncludeValues(t, next, nextResource, def);

                                    for (Object object : values) {
                                        if (object == null) {
                                            continue;
                                        }
                                        if (!(object instanceof BaseResourceReferenceDt)) {
                                            throw new InvalidRequestException("Path '" + next.getValue()
                                                    + "' produced non ResourceReferenceDt value: "
                                                    + object.getClass());
                                        }
                                        BaseResourceReferenceDt rr = (BaseResourceReferenceDt) object;
                                        if (rr.getReference().isEmpty()) {
                                            continue;
                                        }
                                        if (rr.getReference().isLocal()) {
                                            continue;
                                        }

                                        IdDt nextId = rr.getReference().toUnqualified();
                                        if (!previouslyLoadedPids.contains(nextId)) {
                                            includePids.add(nextId);
                                            previouslyLoadedPids.add(nextId);
                                        }
                                    }
                                }
                            }

                            resources = addResourcesAsIncludesById(retVal, includePids, resources);
                        } while (includePids.size() > 0
                                && previouslyLoadedPids.size() < getConfig().getIncludeLimit());

                        if (previouslyLoadedPids.size() >= getConfig().getIncludeLimit()) {
                            OperationOutcome oo = new OperationOutcome();
                            oo.addIssue().setSeverity(IssueSeverityEnum.WARNING).setDetails(
                                    "Not all _include resources were actually included as the request surpassed the limit of "
                                            + getConfig().getIncludeLimit() + " resources");
                            retVal.add(0, oo);
                        }
                    }

                    return retVal;
                }

            });
        }

        @Override
        public Integer preferredPageSize() {
            return theParams.getCount();
        }

        @Override
        public int size() {
            return pids.size();
        }
    };

    ourLog.info("Processed search for {} on {} in {}ms",
            new Object[] { myResourceName, theParams, w.getMillisAndRestart() });

    return retVal;
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TBusApplyinfoEntity> getAllApplications(String coordinatorUserId, String reasonType, String status,
        DateTime startBefore, DateTime startAfter, DateTime endBefore, DateTime endAfter, Integer offset,
        Integer limit, OrderByParam orderByParam, PrincipalExt principalExt) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TBusApplyinfoEntity> cq = cb.createQuery(TBusApplyinfoEntity.class);
    Root<TBusApplyinfoEntity> applyRoot = cq.from(TBusApplyinfoEntity.class);
    applyRoot.fetch(TBusApplyinfoEntity_.passenger);
    Fetch<TBusApplyinfoEntity, TSysUserEntity> fetchCoordinator = applyRoot
            .fetch(TBusApplyinfoEntity_.coordinator);
    applyRoot.fetch(TBusApplyinfoEntity_.department);
    Fetch<TBusApplyinfoEntity, TBusScheduleRelaEntity> scheduleFetch = applyRoot
            .fetch(TBusApplyinfoEntity_.schedule, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.senduser, JoinType.LEFT);
    scheduleFetch.fetch(TBusScheduleRelaEntity_.reciveuser, JoinType.LEFT);
    Fetch<TBusScheduleRelaEntity, TBusScheduleCarEntity> fetchScheduleCar = scheduleFetch
            .fetch(TBusScheduleRelaEntity_.scheduleCars, JoinType.LEFT);
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.car, JoinType.LEFT).fetch(TAzCarinfoEntity_.depot,
            JoinType.LEFT);//  w  ww. ja v a 2  s .  c  om
    fetchScheduleCar.fetch(TBusScheduleCarEntity_.driver, JoinType.LEFT).fetch(TRsDriverinfoEntity_.department,
            JoinType.LEFT);
    Predicate predicate = cb.conjunction();
    if (coordinatorUserId != null) {
        Join<TBusApplyinfoEntity, TSysUserEntity> joinCoordinator = (Join<TBusApplyinfoEntity, TSysUserEntity>) fetchCoordinator;
        predicate = cb.and(predicate, cb.equal(joinCoordinator.get(TSysUserEntity_.userid), coordinatorUserId));
    }
    if (reasonType != null) {
        predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.reason), reasonType));
    }
    if (status != null) {
        if (status.indexOf(":") < 0) {
            predicate = cb.and(predicate, cb.equal(applyRoot.get(TBusApplyinfoEntity_.status), status));
        } else {
            String[] statusList = status.split(":");
            predicate = cb.and(predicate,
                    applyRoot.get(TBusApplyinfoEntity_.status).in(Arrays.asList(statusList)));
        }
    }

    if (startBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startBefore));
    }

    if (startAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.begintime), startAfter));
    }

    if (endBefore != null) {
        predicate = cb.and(predicate,
                cb.lessThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endBefore));
    }

    if (endAfter != null) {
        predicate = cb.and(predicate,
                cb.greaterThanOrEqualTo(applyRoot.get(TBusApplyinfoEntity_.endtime), endAfter));
    }

    cq.where(predicate);

    List<Order> orders = new ArrayList<>();
    if (orderByParam != null) {
        for (OrderByParam.OrderBy orderBy : orderByParam.getOrderBies()) {
            Order order = null;
            if (orderBy.getFiled().toLowerCase().equals("start".toLowerCase())) {
                order = cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime));
            }
            if (order != null && !orderBy.isAsc()) {
                order = order.reverse();
            }
            if (order != null) {
                orders.add(order);
            }
        }

    }
    if (orders.size() == 0) {
        cq.orderBy(cb.desc(applyRoot.get(TBusApplyinfoEntity_.begintime)));
    } else {
        cq.orderBy(orders);
    }

    TypedQuery<TBusApplyinfoEntity> query = em.createQuery(cq);

    if (offset != null) {
        query.setFirstResult(offset);
    }
    if (limit != null) {
        query.setMaxResults(limit);
    }

    applySecurityFilter("applications", principalExt);

    return query.getResultList();
}

From source file:org.agric.oxm.utils.JpaUtils.java

/**
 * Copy Criteria without Selection/* w w  w .jav a  2  s . c o  m*/
 * 
 * @param from
 *            source Criteria
 * @param to
 *            destination Criteria
 */
public static void copyCriteriaNoSelection(CriteriaQuery<?> from, CriteriaQuery<?> to) {

    // Copy Roots
    for (Root<?> root : from.getRoots()) {
        Root<?> dest = to.from(root.getJavaType());
        dest.alias(getOrCreateAlias(root));
        copyJoins(root, dest);
    }

    to.groupBy(from.getGroupList());
    to.distinct(from.isDistinct());
    to.having(from.getGroupRestriction());
    to.where(from.getRestriction());
    to.orderBy(from.getOrderList());
}