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: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  . java  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()))));
        }
    }

    //??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:com.sammyun.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, List<Filter> filters) {
    if (criteriaQuery == null || filters == null || filters.isEmpty()) {
        return;/*from   w  ww  .  jav  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();
    for (Filter filter : filters) {
        if (filter == null || StringUtils.isEmpty(filter.getProperty())) {
            continue;
        }

        /**  */
        if (filter.getMold() == Mold.dl || filter.getMold() == Mold.dg) {
            if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lessThan(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.greaterThan(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                restrictions = criteriaBuilder.and(restrictions,
                        criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                DateUtil.parseDate(filter.getValue().toString())));
            }

        } else {

            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:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateQuantity(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }/*ww  w.j  a v  a  2s.c o m*/

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

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

        String systemValue;
        String unitsValue;
        QuantityCompararatorEnum cmpValue;
        BigDecimal valueValue;
        boolean approx = false;

        if (params instanceof BaseQuantityDt) {
            BaseQuantityDt param = (BaseQuantityDt) params;
            systemValue = param.getSystemElement().getValueAsString();
            unitsValue = param.getUnitsElement().getValueAsString();
            cmpValue = QuantityCompararatorEnum.VALUESET_BINDER
                    .fromCodeString(param.getComparatorElement().getValueAsString());
            valueValue = param.getValueElement().getValue();
        } else if (params instanceof QuantityParam) {
            QuantityParam param = (QuantityParam) params;
            systemValue = param.getSystem().getValueAsString();
            unitsValue = param.getUnits();
            cmpValue = param.getComparator();
            valueValue = param.getValue().getValue();
            approx = param.isApproximate();
        } else {
            throw new IllegalArgumentException("Invalid quantity type: " + params.getClass());
        }

        Predicate system = null;
        if (!isBlank(systemValue)) {
            system = builder.equal(from.get("mySystem"), systemValue);
        }

        Predicate code = null;
        if (!isBlank(unitsValue)) {
            code = builder.equal(from.get("myUnits"), unitsValue);
        }

        Predicate num;
        if (cmpValue == null) {
            BigDecimal mul = approx ? new BigDecimal(0.1) : new BigDecimal(0.01);
            BigDecimal low = valueValue.subtract(valueValue.multiply(mul));
            BigDecimal high = valueValue.add(valueValue.multiply(mul));
            Predicate lowPred = builder.gt(from.get("myValue").as(BigDecimal.class), low);
            Predicate highPred = builder.lt(from.get("myValue").as(BigDecimal.class), high);
            num = builder.and(lowPred, highPred);
        } else {
            switch (cmpValue) {
            case GREATERTHAN:
                Expression<Number> path = from.get("myValue");
                num = builder.gt(path, valueValue);
                break;
            case GREATERTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.ge(path, valueValue);
                break;
            case LESSTHAN:
                path = from.get("myValue");
                num = builder.lt(path, valueValue);
                break;
            case LESSTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.le(path, valueValue);
                break;
            default:
                throw new IllegalStateException(cmpValue.getCode());
            }
        }

        if (system == null && code == null) {
            codePredicates.add(num);
        } else if (system == null) {
            Predicate singleCode = builder.and(code, num);
            codePredicates.add(singleCode);
        } else if (code == null) {
            Predicate singleCode = builder.and(system, num);
            codePredicates.add(singleCode);
        } else {
            Predicate singleCode = builder.and(system, code, num);
            codePredicates.add(singleCode);
        }
    }

    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.sammyun.dao.impl.BaseDaoImpl.java

private void addRestrictions(CriteriaQuery<T> criteriaQuery, Pageable pageable) {
    if (criteriaQuery == null || pageable == null) {
        return;/*w w  w  . j ava2 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();
    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.getMold() == Mold.dl || filter.getMold() == Mold.dg) {
                if (filter.getOperator() == Operator.lt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.lessThan(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.gt && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.greaterThan(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.le && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.lessThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                } else if (filter.getOperator() == Operator.ge && filter.getValue() != null) {
                    restrictions = criteriaBuilder.and(restrictions,
                            criteriaBuilder.greaterThanOrEqualTo(root.<Date>get(filter.getProperty()),
                                    DateUtil.parseDate(filter.getValue().toString())));
                }
            } else {

                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);
}