Example usage for javax.persistence.criteria CriteriaBuilder le

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

Introduction

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

Prototype

Predicate le(Expression<? extends Number> x, Number 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:net.groupbuy.dao.impl.ReviewDaoImpl.java

public Page<Review> findPage(Member member, Product product, Type type, Boolean isShow, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);//from w  w  w  . j  ava 2  s  .  c  o  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

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

public Long count(Member member, Product product, Type type, Boolean isShow) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);/*  w  w  w  . j  a  v a 2  s .  c  o  m*/
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

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

public List<Review> findList(Member member, Product product, Type type, Boolean isShow, Integer count,
        List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Review> criteriaQuery = criteriaBuilder.createQuery(Review.class);
    Root<Review> root = criteriaQuery.from(Review.class);
    criteriaQuery.select(root);//from   w  ww.  ja  va  2  s  . co m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (product != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("product"), product));
    }
    if (type == Type.positive) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.ge(root.<Number>get("score"), 4));
    } else if (type == Type.moderate) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.<Number>get("score"), 3));
    } else if (type == Type.negative) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.le(root.<Number>get("score"), 2));
    }
    if (isShow != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isShow"), isShow));
    }
    criteriaQuery.where(restrictions);
    return super.findList(criteriaQuery, null, count, filters, orders);
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
public List<HotelInfo> searchAvailableHotel(HotelSearchCriteria sc) {

    List<HotelInfo> hotelInfos = null;

    try {/* w w w  . j a  v a  2 s .co m*/
        //body
        CriteriaBuilder cb = getEm().getCriteriaBuilder();

        CriteriaQuery<HotelInfo> cq = cb.createQuery(HotelInfo.class);
        Root<HotelInfo> root = cq.from(HotelInfo.class);
        root.alias("h");

        List<Predicate> predicates = new ArrayList<Predicate>();

        Predicate predicate = cb.equal(root.get(HotelInfo_.cityId), sc.getCityId());
        predicates.add(predicate);

        /**
         * ratePlanStatus-1???)  yfddai 2015-1-8
         */
        predicate = cb.notEqual(root.get(HotelInfo_.ratePlanStatus), -1);
        predicates.add(predicate);

        if (sc.getDistrictId() > 0) {
            predicate = cb.equal(root.get(HotelInfo_.areaId), sc.getDistrictId());
            predicates.add(predicate);
        }

        if (sc.getHotelName() != null && sc.getHotelName().trim().length() > 0) {
            predicate = cb.like(root.get(HotelInfo_.hotelName), "%" + sc.getHotelName() + "%");
            predicates.add(predicate);
        }

        if (sc.getStar() != null && sc.getStar().length() > 0) {
            Join<HotelInfo, HotelAward> hotelAward = root.join("hotelAwards", JoinType.LEFT);
            hotelAward.alias("ha");

            predicates.add(cb.equal(hotelAward.get("provider"), "HotelStarRate"));

            String[] stars = sc.getStar().split(",");
            Predicate p0 = cb.disjunction();
            for (String star : stars) {
                if (star.length() == 0)
                    continue;
                int starLevel = Integer.parseInt(star);
                if (starLevel == 2)
                    p0 = cb.or(p0, cb.le(hotelAward.get(HotelAward_.rating), starLevel));
                else
                    p0 = cb.or(p0, cb.equal(hotelAward.get("rating"), starLevel));
            }
            predicates.add(p0);
        }

        if (sc.getZoneId() > 0) {
            Join<HotelInfo, HotelAddressZone> hotelZone = root.join(HotelInfo_.hotelAddressZones,
                    JoinType.LEFT);
            hotelZone.alias("hz");

            predicate = cb.equal(hotelZone.get(HotelAddressZone_.zoneCode), sc.getZoneId());
            predicates.add(predicate);
        }

        // count items
        CriteriaQuery<Long> cq0 = cb.createQuery(Long.class);
        Root<HotelInfo> root0 = cq0.from(HotelInfo.class);
        root0.alias("h");
        if (sc.getStar() != null && sc.getStar().length() > 0) {
            Join<HotelInfo, HotelAward> hotelAward0 = root0.join("hotelAwards", JoinType.LEFT);
            hotelAward0.alias("ha");
        }
        if (sc.getZoneId() > 0) {
            Join<HotelInfo, HotelAddressZone> hotelZone0 = root0.join(HotelInfo_.hotelAddressZones,
                    JoinType.LEFT);
            hotelZone0.alias("hz");
        }
        cq0.select(cb.count(root0)).where(predicates.toArray(new Predicate[0]));
        Long count = getEm().createQuery(cq0).getSingleResult();

        sc.getPage().setRowCount(count.intValue());

        int firstPosition = (sc.getPage().getPageNo() - 1) * sc.getPage().getPageSize();
        cq.select(root).where(predicates.toArray(new Predicate[0]));

        hotelInfos = getEm().createQuery(cq).setFirstResult(firstPosition)
                .setMaxResults(sc.getPage().getPageSize()).getResultList();
    } catch (PersistenceException e) {
        logger.error(e.getMessage());
    }

    return hotelInfos == null ? new ArrayList<HotelInfo>() : hotelInfos;
}

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

private Predicate createPredicateNumeric(CriteriaBuilder builder, IQueryParameterType params,
        ParamPrefixEnum cmpValue, BigDecimal valueValue, final Expression<BigDecimal> path,
        String invalidMessageName, String theValueString) {
    Predicate num;/*ww w  .  jav a2  s . com*/
    switch (cmpValue) {
    case GREATERTHAN:
        num = builder.gt(path, valueValue);
        break;
    case GREATERTHAN_OR_EQUALS:
        num = builder.ge(path, valueValue);
        break;
    case LESSTHAN:
        num = builder.lt(path, valueValue);
        break;
    case LESSTHAN_OR_EQUALS:
        num = builder.le(path, valueValue);
        break;
    case APPROXIMATE:
    case EQUAL:
    case NOT_EQUAL:
        BigDecimal mul = calculateFuzzAmount(cmpValue, valueValue);
        BigDecimal low = valueValue.subtract(mul, MathContext.DECIMAL64);
        BigDecimal high = valueValue.add(mul, MathContext.DECIMAL64);
        Predicate lowPred;
        Predicate highPred;
        if (cmpValue != ParamPrefixEnum.NOT_EQUAL) {
            lowPred = builder.ge(path.as(BigDecimal.class), low);
            highPred = builder.le(path.as(BigDecimal.class), high);
            num = builder.and(lowPred, highPred);
            ourLog.trace("Searching for {} <= val <= {}", low, high);
        } else {
            // Prefix was "ne", so reverse it!
            lowPred = builder.lt(path.as(BigDecimal.class), low);
            highPred = builder.gt(path.as(BigDecimal.class), high);
            num = builder.or(lowPred, highPred);
        }
        break;
    default:
        String msg = myContext.getLocalizer().getMessage(SearchBuilder.class, invalidMessageName,
                cmpValue.getValue(), params.getValueAsQueryToken(myContext));
        throw new InvalidRequestException(msg);
    }
    return num;
}

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

private Set<Long> addPredicateNumber(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }//w w  w  . j av  a2s.  c  o m

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamNumber> from = cq.from(ResourceIndexedSearchParamNumber.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType params = nextOr;

        if (params instanceof NumberParam) {
            NumberParam param = (NumberParam) params;

            BigDecimal value = param.getValue();
            if (value == null) {
                return thePids;
            }

            Path<Object> fromObj = from.get("myValue");
            if (param.getComparator() == null) {
                double mul = value.doubleValue() * 1.01;
                double low = value.doubleValue() - mul;
                double high = value.doubleValue() + mul;
                Predicate lowPred = builder.ge(fromObj.as(Long.class), low);
                Predicate highPred = builder.le(fromObj.as(Long.class), high);
                codePredicates.add(builder.and(lowPred, highPred));
            } else {
                switch (param.getComparator()) {
                case GREATERTHAN:
                    codePredicates.add(builder.greaterThan(fromObj.as(BigDecimal.class), value));
                    break;
                case GREATERTHAN_OR_EQUALS:
                    codePredicates.add(builder.ge(fromObj.as(BigDecimal.class), value));
                    break;
                case LESSTHAN:
                    codePredicates.add(builder.lessThan(fromObj.as(BigDecimal.class), value));
                    break;
                case LESSTHAN_OR_EQUALS:
                    codePredicates.add(builder.le(fromObj.as(BigDecimal.class), value));
                    break;
                }
            }
        } else {
            throw new IllegalArgumentException("Invalid token type: " + params.getClass());
        }

    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    if (criteriaQuery == null || filters == null || filters.isEmpty()) {
        return;/*from   w  w w  . j a  v a 2 s . c  o m*/
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction()
            : criteriaBuilder.conjunction();
    for (Filter filter : filters) {
        if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
            continue;
        }
        if (filter.getOperator() == Operator.eq && filter.getValue() != null) {
            if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                ((String) filter.getValue()).toLowerCase()));
            } else {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue()));
            }
        } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) {
            if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.notEqual(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                ((String) filter.getValue()).toLowerCase()));
            } else {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue()));
            }
        } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
        } else if (filter.getOperator() == Operator.like && filter.getValue() != null
                && filter.getValue() instanceof String) {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.like(root.<String>get(filter.getProperty()), (String) filter.getValue()));
        } else if (filter.getOperator() == Operator.in && filter.getValue() != null) {
            restrictions = criteriaBuilder.and(restrictions,
                    root.get(filter.getProperty()).in(filter.getValue()));
        } else if (filter.getOperator() == Operator.isNull) {
            restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull());
        } else if (filter.getOperator() == Operator.isNotNull) {
            restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull());
        }
    }
    criteriaQuery.where(restrictions);
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    if (criteriaQuery == null || pageable == null) {
        return;//from   w  w  w . ja v  a 2s  . c o m
    }
    Root<T> root = getRoot(criteriaQuery);
    if (root == null) {
        return;
    }
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    Predicate restrictions = criteriaQuery.getRestriction() != null ? criteriaQuery.getRestriction()
            : criteriaBuilder.conjunction();
    if (StringUtils.isNotEmpty(pageable.getSearchProperty())
            && StringUtils.isNotEmpty(pageable.getSearchValue())) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                .like(root.<String>get(pageable.getSearchProperty()), "%" + pageable.getSearchValue() + "%"));
    }
    if (pageable.getFilters() != null) {
        for (Filter filter : pageable.getFilters()) {
            if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
                continue;
            }
            if (filter.getOperator() == Operator.eq && filter.getValue() != null) {
                if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                        && filter.getValue() instanceof String) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.equal(criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                    ((String) filter.getValue()).toLowerCase()));
                } else {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.equal(root.get(filter.getProperty()), filter.getValue()));
                }
            } else if (filter.getOperator() == Operator.ne && filter.getValue() != null) {
                if (filter.getIgnoreCase() != null && filter.getIgnoreCase()
                        && filter.getValue() instanceof String) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.notEqual(
                                    criteriaBuilder.lower(root.<String>get(filter.getProperty())),
                                    ((String) filter.getValue()).toLowerCase()));
                } else {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.notEqual(root.get(filter.getProperty()), filter.getValue()));
                }
            } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.gt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lt(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.ge(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.le(root.<Number>get(filter.getProperty()), (Number) filter.getValue()));
            } else if (filter.getOperator() == Operator.like && filter.getValue() != null
                    && filter.getValue() instanceof String) {
                restrictions = criteriaBuilder.and(restrictions, criteriaBuilder
                        .like(root.<String>get(filter.getProperty()), (String) filter.getValue()));
            } else if (filter.getOperator() == Operator.in && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        root.get(filter.getProperty()).in(filter.getValue()));
            } else if (filter.getOperator() == Operator.isNull) {
                restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNull());
            } else if (filter.getOperator() == Operator.isNotNull) {
                restrictions = criteriaBuilder.and(restrictions, root.get(filter.getProperty()).isNotNull());
            }
        }
    }
    criteriaQuery.where(restrictions);
}

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);/* ww  w.j a  v  a2 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);
    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);// w w  w .  j av  a2s .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);
    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);
}