Example usage for javax.persistence.criteria CriteriaBuilder isNull

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

Introduction

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

Prototype

Predicate isNull(Expression<?> x);

Source Link

Document

Create a predicate to test whether the expression is null.

Usage

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

private void addPredicateParamMissing(String joinName, String theParamName,
        Class<? extends BaseResourceIndexedSearchParam> theParamTable) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<? extends BaseResourceIndexedSearchParam> subQfrom = subQ.from(theParamTable);
    subQ.select(subQfrom.get("myResourcePid").as(Long.class));
    Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
    Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
    subQ.where(builder.and(subQtype, subQname));

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));

    cq.where(builder.and(toArray(predicates)));

    ourLog.info("Adding :missing qualifier for parameter '{}'", theParamName);

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());// w  w  w  .  j  a  v  a 2  s  .  c  o m
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private List<HmFolder> findRootFolders() {
    Specification<HmFolder> spec = new Specification<HmFolder>() {
        @Override/*from   ww  w.  j ava2 s  .co  m*/
        public Predicate toPredicate(Root<HmFolder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate[] predicates = new Predicate[1];
            predicates[0] = cb.isNull(root.get("parent"));
            return cb.and(predicates);
        }
    };
    return rep.findAll(spec);
}

From source file:com.aerohive.nms.web.config.lbs.services.HmFolderServiceImpl.java

private HmFolder findRootFolder(final Long ownerId) {
    Specification<HmFolder> spec = new Specification<HmFolder>() {
        @Override//w  w  w.  j  a v a 2  s  . co m
        public Predicate toPredicate(Root<HmFolder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Predicate[] predicates = new Predicate[2];
            predicates[0] = cb.isNull(root.get("parent"));
            predicates[1] = cb.equal(root.get("ownerId"), ownerId);
            return cb.and(predicates);
        }
    };
    List<HmFolder> all = rep.findAll(spec);
    return all.isEmpty() ? null : all.get(0);
}

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

private void addPredicateLanguage(List<List<? extends IQueryParameterType>> theList) {
    for (List<? extends IQueryParameterType> nextList : theList) {

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

        Set<String> values = new HashSet<String>();
        for (IQueryParameterType next : nextList) {
            if (next instanceof StringParam) {
                String nextValue = ((StringParam) next).getValue();
                if (isBlank(nextValue)) {
                    continue;
                }/*from ww  w  .  j  a  v  a  2s . com*/
                values.add(nextValue);
            } else {
                throw new InternalErrorException(
                        "Lanugage parameter must be of type " + StringParam.class.getCanonicalName() + " - Got "
                                + next.getClass().getCanonicalName());
            }
        }

        if (values.isEmpty()) {
            continue;
        }

        List<Predicate> predicates = new ArrayList<Predicate>();
        predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        predicates.add(from.get("myLanguage").as(String.class).in(values));
        createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
        createPredicateLastUpdatedForResourceTable(builder, from, predicates);

        predicates.add(builder.isNull(from.get("myDeleted")));

        cq.where(toArray(predicates));

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        doSetPids(q.getResultList());
        if (doHaveNoResults()) {
            return;
        }
    }

    return;
}

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

private Predicate createPredicateToken(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> theFrom) {
    String code;//from   w  w  w  . j a v  a 2s . c o m
    String system;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        system = id.getSystem();
        code = id.getValue();
    } else if (theParameter instanceof BaseIdentifierDt) {
        BaseIdentifierDt id = (BaseIdentifierDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = id.getValueElement().getValue();
    } else if (theParameter instanceof BaseCodingDt) {
        BaseCodingDt id = (BaseCodingDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = id.getCodeElement().getValue();
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (system != null && system.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has system (" + system.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + system);
    }
    if (code != null && code.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has code (" + code.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + code);
    }

    ArrayList<Predicate> singleCodePredicates = (new ArrayList<Predicate>());
    if (StringUtils.isNotBlank(system)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("mySystem"), system));
    } else if (system == null) {
        // don't check the system
    } else {
        // If the system is "", we only match on null systems
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("mySystem")));
    }
    if (StringUtils.isNotBlank(code)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("myValue"), code));
    } else {
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("myValue")));
    }
    Predicate singleCode = theBuilder.and(singleCodePredicates.toArray(new Predicate[0]));
    return singleCode;
}

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

private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName,
        DateRangeParam theLastUpdated) {
    TagTypeEnum tagType;//  w  w w. j  a va 2  s  .  com
    if (Constants.PARAM_TAG.equals(theParamName)) {
        tagType = TagTypeEnum.TAG;
    } else if (Constants.PARAM_PROFILE.equals(theParamName)) {
        tagType = TagTypeEnum.PROFILE;
    } else if (Constants.PARAM_SECURITY.equals(theParamName)) {
        tagType = TagTypeEnum.SECURITY_LABEL;
    } else {
        throw new IllegalArgumentException("Param name: " + theParamName); // shouldn't happen
    }

    /*
     * CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq =
     * builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class);
     * cq.select(from.get("myId").as(Long.class));
     * 
     * Subquery<Long> subQ = cq.subquery(Long.class); Root<? extends BaseResourceIndexedSearchParam> subQfrom =
     * subQ.from(theParamTable); subQ.select(subQfrom.get("myResourcePid").as(Long.class));
     * Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName); Predicate subQtype =
     * builder.equal(subQfrom.get("myResourceType"), myResourceName);
     * subQ.where(builder.and(subQtype, subQname));
     * 
     * List<Predicate> predicates = new ArrayList<Predicate>();
     * predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
     * predicates.add(builder.equal(from.get("myResourceType"),
     * myResourceName)); predicates.add(builder.isNull(from.get("myDeleted"))); createPredicateResourceId(builder, cq,
     * predicates, from.get("myId").as(Long.class));
     */

    List<Pair<String, String>> notTags = Lists.newArrayList();
    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        for (IQueryParameterType nextOrParams : nextAndParams) {
            if (nextOrParams instanceof TokenParam) {
                TokenParam param = (TokenParam) nextOrParams;
                if (param.getModifier() == TokenParamModifier.NOT) {
                    if (isNotBlank(param.getSystem()) || isNotBlank(param.getValue())) {
                        notTags.add(Pair.of(param.getSystem(), param.getValue()));
                    }
                }
            }
        }
    }

    /*
     * We have a parameter of ResourceType?_tag:not=foo This means match resources that don't have the given tag(s)
     */
    if (notTags.isEmpty() == false) {
        // CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        // CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        // Root<ResourceTable> from = cq.from(ResourceTable.class);
        // cq.select(from.get("myId").as(Long.class));
        //
        // Subquery<Long> subQ = cq.subquery(Long.class);
        // Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
        // subQ.select(subQfrom.get("myResourceId").as(Long.class));
        // Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
        // Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
        // subQ.where(builder.and(subQtype, subQname));
        //
        // List<Predicate> predicates = new ArrayList<Predicate>();
        // predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
        // predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        // predicates.add(builder.isNull(from.get("myDeleted")));
        // createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    }

    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        boolean haveTags = false;
        for (IQueryParameterType nextParamUncasted : nextAndParams) {
            if (nextParamUncasted instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                } else if (isNotBlank(nextParam.getSystem())) {
                    throw new InvalidRequestException("Invalid " + theParamName
                            + " parameter (must supply a value/code and not just a system): "
                            + nextParam.getValueAsQueryToken(myContext));
                }
            } else {
                UriParam nextParam = (UriParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                }
            }
        }
        if (!haveTags) {
            continue;
        }

        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();

        boolean paramInverted = false;
        List<Pair<String, String>> tokens = Lists.newArrayList();
        for (IQueryParameterType nextOrParams : nextAndParams) {
            String code;
            String system;
            if (nextOrParams instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextOrParams;
                code = nextParam.getValue();
                system = nextParam.getSystem();
                if (nextParam.getModifier() == TokenParamModifier.NOT) {
                    paramInverted = true;
                }
            } else {
                UriParam nextParam = (UriParam) nextOrParams;
                code = nextParam.getValue();
                system = null;
            }

            if (isNotBlank(code)) {
                tokens.add(Pair.of(system, code));
            }
        }

        if (tokens.isEmpty()) {
            continue;
        }

        if (paramInverted) {
            ourLog.debug("Searching for _tag:not");

            CriteriaQuery<Long> cq = builder.createQuery(Long.class);
            Root<ResourceTable> newFrom = cq.from(ResourceTable.class);

            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
            subQ.select(subQfrom.get("myResourceId").as(Long.class));

            cq.select(newFrom.get("myId").as(Long.class));

            List<Predicate> andPredicates = new ArrayList<Predicate>();
            andPredicates = new ArrayList<Predicate>();
            andPredicates.add(builder.equal(newFrom.get("myResourceType"), myResourceName));
            andPredicates.add(builder.not(builder.in(newFrom.get("myId")).value(subQ)));

            Subquery<Long> defJoin = subQ.subquery(Long.class);
            Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class);
            defJoin.select(defJoinFrom.get("myId").as(Long.class));

            subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin));

            List<Predicate> orPredicates = createPredicateTagList(defJoinFrom, builder, tagType, tokens);
            defJoin.where(toArray(orPredicates));

            cq.where(toArray(andPredicates));

            TypedQuery<Long> q = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>(q.getResultList());
            doSetPids(pids);
            continue;
        }

        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        Root<ResourceTag> from = cq.from(ResourceTag.class);
        List<Predicate> andPredicates = new ArrayList<Predicate>();
        andPredicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        From<ResourceTag, TagDefinition> defJoin = from.join("myTag");

        Join<?, ResourceTable> defJoin2 = from.join("myResource");

        Predicate notDeletedPredicatePrediate = builder.isNull(defJoin2.get("myDeleted"));
        andPredicates.add(notDeletedPredicatePrediate);

        List<Predicate> orPredicates = createPredicateTagList(defJoin, builder, tagType, tokens);
        andPredicates.add(builder.or(toArray(orPredicates)));

        if (theLastUpdated != null) {
            andPredicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, defJoin2));
        }

        createPredicateResourceId(builder, cq, andPredicates, from.get("myResourceId").as(Long.class));
        Predicate masterCodePredicate = builder.and(toArray(andPredicates));

        cq.select(from.get("myResourceId").as(Long.class));
        cq.where(masterCodePredicate);

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

}

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);/*w w  w.ja  v  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()))));
        }
    }
    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.java2s.  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);
}

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 .  ja  v a 2 s  . c  om*/
    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:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private Predicate createPredicateToken(IQueryParameterType theParameter, String theParamName,
        CriteriaBuilder theBuilder,
        From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> theFrom) {
    String code;/* w  w w  .ja va  2 s . c om*/
    String system;
    TokenParamModifier modifier = null;
    if (theParameter instanceof TokenParam) {
        TokenParam id = (TokenParam) theParameter;
        system = id.getSystem();
        code = (id.getValue());
        modifier = id.getModifier();
    } else if (theParameter instanceof BaseIdentifierDt) {
        BaseIdentifierDt id = (BaseIdentifierDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getValueElement().getValue());
    } else if (theParameter instanceof BaseCodingDt) {
        BaseCodingDt id = (BaseCodingDt) theParameter;
        system = id.getSystemElement().getValueAsString();
        code = (id.getCodeElement().getValue());
    } else {
        throw new IllegalArgumentException("Invalid token type: " + theParameter.getClass());
    }

    if (system != null && system.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has system (" + system.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + system);
    }

    if (code != null && code.length() > ResourceIndexedSearchParamToken.MAX_LENGTH) {
        throw new InvalidRequestException("Parameter[" + theParamName + "] has code (" + code.length()
                + ") that is longer than maximum allowed (" + ResourceIndexedSearchParamToken.MAX_LENGTH + "): "
                + code);
    }

    /*
     * Process token modifiers (:in, :below, :above)
     */

    List<VersionIndependentConcept> codes = null;
    if (modifier == TokenParamModifier.IN) {
        codes = myTerminologySvc.expandValueSet(code);
    } else if (modifier == TokenParamModifier.ABOVE) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesAbove(system, code);
    } else if (modifier == TokenParamModifier.BELOW) {
        system = determineSystemIfMissing(theParamName, code, system);
        codes = myTerminologySvc.findCodesBelow(system, code);
    }

    if (codes != null) {
        if (codes.isEmpty()) {
            return null;
        }
        List<Predicate> orPredicates = new ArrayList<Predicate>();
        for (VersionIndependentConcept nextCode : codes) {
            Predicate systemPredicate = theBuilder.equal(theFrom.get("mySystem"), nextCode.getSystem());
            Predicate codePredicate = theBuilder.equal(theFrom.get("myValue"), nextCode.getCode());
            orPredicates.add(theBuilder.and(systemPredicate, codePredicate));
        }

        return theBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]));
    }

    /*
     * Ok, this is a normal query
     */

    ArrayList<Predicate> singleCodePredicates = (new ArrayList<Predicate>());
    if (StringUtils.isNotBlank(system)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("mySystem"), system));
    } else if (system == null) {
        // don't check the system
    } else {
        // If the system is "", we only match on null systems
        singleCodePredicates.add(theBuilder.isNull(theFrom.get("mySystem")));
    }

    if (StringUtils.isNotBlank(code)) {
        singleCodePredicates.add(theBuilder.equal(theFrom.get("myValue"), code));
    } else {
        /*
         * As of HAPI FHIR 1.5, if the client searched for a token with a system but no specified value this means to
         * match all tokens with the given value.
         * 
         * I'm not sure I agree with this, but hey.. FHIR-I voted and this was the result :)
         */
        // singleCodePredicates.add(theBuilder.isNull(theFrom.get("myValue")));
    }

    Predicate singleCode = theBuilder.and(toArray(singleCodePredicates));
    return singleCode;
}