Example usage for javax.persistence.criteria CriteriaBuilder lessThanOrEqualTo

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

Introduction

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

Prototype

<Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(Expression<? extends Y> x, Y y);

Source Link

Document

Create a predicate for testing whether the first argument is less than or equal to the second.

Usage

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);/*from w ww  .  j a  v  a  2 s. com*/
    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:net.shopxx.dao.impl.OrderDaoImpl.java

public Page<Order> findPage(Order.Type type, Order.Status status, Member member, Goods goods,
        Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint,
        Boolean isAllocatedStock, Boolean hasExpired, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);//from   w ww.j av a2s  . c  om
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

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

public Long count(Order.Type type, Order.Status status, Member member, Goods goods, Boolean isPendingReceive,
        Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint, Boolean isAllocatedStock,
        Boolean hasExpired) {/*from www.  ja va 2  s  .c  o  m*/
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

public List<Order> findList(Order.Type type, Order.Status status, Member member, Goods goods,
        Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint,
        Boolean isAllocatedStock, Boolean hasExpired, Integer count, List<Filter> filters,
        List<net.shopxx.Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);//from  w w w  .j  a va 2  s. c om
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findList(criteriaQuery, null, count, filters, orders);
}

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

public List<Statistic> analyze(Statistic.Period period, Date beginDate, Date endDate) {
    Assert.notNull(period);//  ww  w . j  av  a  2  s .  co m

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Statistic> criteriaQuery = criteriaBuilder.createQuery(Statistic.class);
    Root<Statistic> root = criteriaQuery.from(Statistic.class);
    switch (period) {
    case year:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"));
        break;
    case month:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                criteriaBuilder.sum(root.<Long>get("registerMemberCount")),
                criteriaBuilder.sum(root.<Long>get("createOrderCount")),
                criteriaBuilder.sum(root.<Long>get("completeOrderCount")),
                criteriaBuilder.sum(root.<BigDecimal>get("createOrderAmount")),
                criteriaBuilder.sum(root.<BigDecimal>get("completeOrderAmount"))));
        criteriaQuery.groupBy(root.get("year"), root.get("month"));
        break;
    case day:
        criteriaQuery.select(criteriaBuilder.construct(Statistic.class, root.get("year"), root.get("month"),
                root.get("day"), root.<Long>get("registerMemberCount"), root.<Long>get("createOrderCount"),
                root.<Long>get("completeOrderCount"), root.<BigDecimal>get("createOrderAmount"),
                root.<BigDecimal>get("completeOrderAmount")));
        break;
    }
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        Calendar calendar = DateUtils.toCalendar(beginDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.greaterThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.greaterThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.greaterThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    if (endDate != null) {
        Calendar calendar = DateUtils.toCalendar(endDate);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.lessThan(root.<Integer>get("year"), year),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.lessThan(root.<Integer>get("month"), month)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.<Integer>get("year"), year),
                                criteriaBuilder.equal(root.<Integer>get("month"), month),
                                criteriaBuilder.lessThanOrEqualTo(root.<Integer>get("day"), day))));
    }
    criteriaQuery.where(restrictions);
    return entityManager.createQuery(criteriaQuery).getResultList();
}

From source file:org.pushio.webapp.support.persistence.DynamicSpecifications.java

/**
 * @see ??JPA//  ww w  . j  av  a  2 s. c o  m
 * @param filters
 * @param entityClazz
 * @param isDistinct  trueSQLdistinctfalse?
 * @return
 */
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz, final boolean isDistinct, final List<OrderParam> orderParams) {
    return new Specification<T>() {
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (orderParams != null && orderParams.size() > 0) {
                /*
                CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
                Root<Foo> from = criteriaQuery.from(Foo.class);
                CriteriaQuery<Foo> select = criteriaQuery.select(from);
                criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
                */
                List<Order> orders = new ArrayList<Order>(orderParams.size());
                for (OrderParam orderParam : orderParams) {
                    if (orderParam != null && orderParam.getField() != null) {
                        String fields[] = StringUtil.split(orderParam.getField(), '.');
                        Path expression = (fields.length > 1) ? root.join(fields[0]) : root.get(fields[0]);
                        for (int i = 1, len = fields.length; i < len; ++i) {
                            expression = expression.get(fields[i]);
                        }
                        if (expression != null) {
                            Order order = (orderParam.getType() == null
                                    || orderParam.getType().equalsIgnoreCase("asc")) ? builder.asc(expression)
                                            : builder.desc(expression);
                            orders.add(order);
                            //                        query.orderBy(order);
                        }
                    }
                }
                query.orderBy(orders);
            }
            query.distinct(isDistinct);
            if (Collections3.isNotEmpty(filters)) {
                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, '.');
                    Path expression = null;

                    //////  ?
                    boolean hasJoin = names[0].startsWith("[join]");
                    String fn = hasJoin ? names[0].substring(6) : names[0];
                    boolean isNotDateType = !(filter.value instanceof Date);
                    try {
                        expression = hasJoin ? root.join(fn) : root.get(fn);
                        if (isNotDateType && isDateType(expression.getJavaType())) {
                            // filter.value??
                            filter.value = parseDate(filter.value.toString(), filter.operator);
                        }
                    } catch (Exception e) {
                        //                     logger.error(e.getMessage(), e);
                        continue; // ??
                    }
                    boolean isPropertyNotValid = false;
                    for (int i = 1; i < names.length; i++) {
                        try {
                            expression = expression.get(names[i]);
                            if (isNotDateType && isDateType(expression.getJavaType())) {
                                filter.value = parseDate(filter.value.toString(), filter.operator);
                            }
                        } catch (Exception e) {
                            //                        logger.error(e.getMessage(), e);
                            isPropertyNotValid = true; // 
                            break; // ??
                        }
                    }
                    if (expression == null || isPropertyNotValid) {
                        continue;
                    }
                    ///////

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ORLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.or(like));
                        }

                        break;
                    case ANDLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.like(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case ANDNOTLIKE:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notLike(expression, "%" + values[i] + "%");
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case OREQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.equal(expression, values[i]);
                            }
                            predicates.add(builder.or(like));
                        }
                        break;

                    case ANDNOTEQ:
                        if (filter.value instanceof String) {
                            String value = (String) filter.value;
                            String[] values = value.split(",");
                            Predicate[] like = new Predicate[values.length];
                            for (int i = 0; i < values.length; i++) {
                                like[i] = builder.notEqual(expression, values[i]);
                            }
                            predicates.add(builder.and(like));
                        }
                        break;
                    case NOTEQ:
                        predicates.add(builder.notEqual(expression, (Comparable) filter.value));
                        break;
                    case NOTLIKE:
                        predicates.add(builder.notLike(expression, "%" + filter.value + "%"));
                        break;
                    case NULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NOTNULL:
                        predicates.add(builder.isNotNull(expression));
                        break;
                    //                  case IN:
                    //                     predicates.add(builder.in(expression).in(values));
                    //                     break;
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

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

public List<Product> findList(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Integer count, List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//from w  ww  .j a  v  a 2s . c  o  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findList(criteriaQuery, null, count, filters, orders);
}

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

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);/*ww w .ja  va2  s .  com*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

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

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable, Set<Supplier> suppliers) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//from w  w  w  .  j  av a 2 s  . c o m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }

    //??ADDbyDanielChen 20140502
    if ((suppliers != null) && !(suppliers.isEmpty())) {
        Expression<Supplier> exp = root.get("supplier");
        restrictions = criteriaBuilder.and(restrictions, exp.in(suppliers));
    }

    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

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

private Predicate generatePredicate(SearchCriteria searchCriteria, EntityManager em,
        CriteriaBuilder criteriaBuilder, Root<VXXTrxLog> rootEntityType) {
    Predicate predicate = criteriaBuilder.conjunction();
    Map<String, Object> paramList = searchCriteria.getParamList();
    if (CollectionUtils.isEmpty(paramList)) {
        return predicate;
    }/*from w ww  .  jav  a 2 s .  c om*/

    Metamodel entityMetaModel = em.getMetamodel();
    EntityType<VXXTrxLog> entityType = entityMetaModel.entity(VXXTrxLog.class);

    for (Map.Entry<String, Object> entry : paramList.entrySet()) {
        String key = entry.getKey();
        for (SearchField searchField : searchFields) {
            if (!key.equalsIgnoreCase(searchField.getClientFieldName())) {
                continue;
            }

            String fieldName = searchField.getFieldName();
            if (!StringUtils.isEmpty(fieldName)) {
                fieldName = fieldName.contains(".") ? fieldName.substring(fieldName.indexOf(".") + 1)
                        : fieldName;
            }

            Object paramValue = entry.getValue();
            boolean isListValue = false;
            if (paramValue != null && paramValue instanceof Collection) {
                isListValue = true;
            }

            // build where clause depending upon given parameters
            if (SearchField.DATA_TYPE.STRING.equals(searchField.getDataType())) {
                // build where clause for String datatypes
                SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                if (attr != null) {
                    Predicate stringPredicate = null;
                    if (SearchField.SEARCH_TYPE.PARTIAL.equals(searchField.getSearchType())) {
                        String val = "%" + paramValue + "%";
                        stringPredicate = criteriaBuilder.like(rootEntityType.get(attr), val);
                    } else {
                        stringPredicate = criteriaBuilder.equal(rootEntityType.get(attr), paramValue);
                    }
                    predicate = criteriaBuilder.and(predicate, stringPredicate);
                }

            } else if (SearchField.DATA_TYPE.INT_LIST.equals(searchField.getDataType())
                    || isListValue && SearchField.DATA_TYPE.INTEGER.equals(searchField.getDataType())) {
                // build where clause for integer lists or integers datatypes
                Collection<Number> intValueList = null;
                if (paramValue != null && (paramValue instanceof Integer || paramValue instanceof Long)) {
                    intValueList = new ArrayList<Number>();
                    intValueList.add((Number) paramValue);
                } else {
                    intValueList = (Collection<Number>) paramValue;
                }
                for (Number value : intValueList) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    if (attr != null) {
                        Predicate intPredicate = criteriaBuilder.equal(rootEntityType.get(attr), value);
                        predicate = criteriaBuilder.and(predicate, intPredicate);
                    }
                }

            } else if (SearchField.DATA_TYPE.DATE.equals(searchField.getDataType())) {
                // build where clause for date datatypes
                Date fieldValue = (Date) paramList.get(searchField.getClientFieldName());
                if (fieldValue != null && searchField.getCustomCondition() == null) {
                    SingularAttribute attr = entityType.getSingularAttribute(fieldName);
                    Predicate datePredicate = null;
                    if (SearchField.SEARCH_TYPE.LESS_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.LESS_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.lessThanOrEqualTo(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThan(rootEntityType.get(attr), fieldValue);
                    } else if (SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN.equals(searchField.getSearchType())) {
                        datePredicate = criteriaBuilder.greaterThanOrEqualTo(rootEntityType.get(attr),
                                fieldValue);
                    } else {
                        datePredicate = criteriaBuilder.equal(rootEntityType.get(attr), fieldValue);
                    }
                    predicate = criteriaBuilder.and(predicate, datePredicate);
                }
            }
        }
    }
    return predicate;
}