Example usage for javax.persistence.criteria CriteriaQuery subquery

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

Introduction

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

Prototype

<U> Subquery<U> subquery(Class<U> type);

Source Link

Document

Create a subquery of the query.

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 ww. j a  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()))));
        }
    }

    //??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.goodhuddle.huddle.repository.MemberSpecification.java

public static Specification<Member> search(final Huddle huddle, final SearchMembersRequest request) {
    return new Specification<Member>() {
        @Override/*from   w  ww .j av  a  2 s .c o m*/
        public Predicate toPredicate(Root<Member> member, CriteriaQuery<?> query, CriteriaBuilder builder) {

            Predicate conjunction = builder.conjunction();

            // huddle
            conjunction.getExpressions().add(builder.equal(member.get("huddle"), huddle));

            // keywords

            if (StringUtils.isNotBlank(request.getKeywords())) {
                String[] terms = StringUtils.split(request.getKeywords());
                for (String keyword : terms) {
                    if (keyword != null && keyword.length() > 0) {

                        String matchTerm = "%" + keyword.toLowerCase() + "%";
                        conjunction.getExpressions().add(builder.or(
                                builder.like(builder.lower(member.<String>get("username")), matchTerm),
                                builder.like(builder.lower(member.<String>get("email")), matchTerm),
                                builder.like(builder.lower(member.<String>get("firstName")), matchTerm),
                                builder.like(builder.lower(member.<String>get("lastName")), matchTerm)));
                    }
                }
            }

            // security groups

            if (CollectionUtils.isNotEmpty(request.getSecurityGroupIds())) {

                Join<Object, Object> securityGroup = member.join("securityGroup",
                        request.isIncludeNoAccess() ? JoinType.LEFT : JoinType.INNER);

                Predicate disjunction = builder.disjunction();
                for (Long id : request.getSecurityGroupIds()) {
                    disjunction.getExpressions().add(builder.equal(securityGroup.get("id"), id));
                }
                if (request.isIncludeNoAccess()) {
                    disjunction.getExpressions().add(builder.isNull(securityGroup.get("id")));
                }
                conjunction.getExpressions().add(disjunction);

            } else if (request.isIncludeNoAccess()) {

                conjunction.getExpressions().add(builder.isNull(member.get("securityGroup")));

            }

            // tags

            MemberTagFilter tagFilter = request.getTags();
            if (tagFilter != null) {

                if (tagFilter.getIncluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getIncluded().getTagIds())) {

                        MemberTagFilter.TagSet included = request.getTags().getIncluded();
                        MatchType matchType = included.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.conjunction()
                                : builder.disjunction();

                        for (Long tagId : included.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq));
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

                if (tagFilter.getExcluded() != null) {

                    if (CollectionUtils.isNotEmpty(tagFilter.getExcluded().getTagIds())) {

                        MemberTagFilter.TagSet excluded = request.getTags().getExcluded();
                        MatchType matchType = excluded.getMatchType();
                        Predicate tagPredicate = matchType.equals(MatchType.all) ? builder.disjunction()
                                : builder.conjunction();

                        for (Long tagId : excluded.getTagIds()) {
                            Subquery<Member> sq = query.subquery(Member.class);
                            Root<Member> subMember = sq.from(Member.class);
                            Join<Member, Tag> tag = subMember.join("tags");
                            sq.select(subMember).where(builder.equal(tag.get("id"), tagId));
                            tagPredicate.getExpressions().add(builder.in(member).value(sq).not());
                        }

                        conjunction.getExpressions().add(tagPredicate);
                    }
                }

            }

            return conjunction;
        }
    };
}

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

private void addPredicateParamMissingResourceLink(String joinName, String theParamName) {
    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<ResourceLink> subQfrom = subQ.from(ResourceLink.class);
    subQ.select(subQfrom.get("mySourceResourcePid").as(Long.class));

    // subQ.where(builder.equal(subQfrom.get("myParamName"), theParamName));
    Predicate path = createResourceLinkPathPredicate(theParamName, subQfrom);
    subQ.where(path);//from ww w . j  av  a2  s  .  c o m

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

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

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

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());//  ww  w  .  j  a  v a2 s  .  c  om
}

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

private void createPredicateResourceId(CriteriaBuilder builder, CriteriaQuery<?> cq,
        List<Predicate> thePredicates, Expression<Long> theExpression) {
    if (myParams.isPersistResults()) {
        if (mySearchEntity.getTotalCount() > -1) {
            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<SearchResult> subQfrom = subQ.from(SearchResult.class);
            subQ.select(subQfrom.get("myResourcePid").as(Long.class));
            Predicate subQname = builder.equal(subQfrom.get("mySearch"), mySearchEntity);
            subQ.where(subQname);/*from w  w w  .j  a va 2  s  .  com*/

            thePredicates.add(theExpression.in(subQ));
        }
    } else {
        if (myPids != null) {
            thePredicates.add(theExpression.in(myPids));
        }
    }

}

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  ww.  j a  va2s.c o m
    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:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * {@inheritDoc}// w  ww . ja va  2 s. c  om
 */
@Override
public BusinessObjectDataEntity getBusinessObjectDataByAltKeyAndStatus(
        BusinessObjectDataKey businessObjectDataKey, String businessObjectDataStatus) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> businessObjectDataEntity = criteria.from(BusinessObjectDataEntity.class);

    // Join to other tables that we need to filter on.
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate mainQueryRestriction = getQueryRestriction(builder, businessObjectDataEntity,
            businessObjectFormatEntity, fileTypeEntity, businessObjectDefinitionEntity, businessObjectDataKey);

    // If a format version was specified, use the latest available for this partition value.
    if (businessObjectDataKey.getBusinessObjectFormatVersion() == null) {
        // Business object format version is not specified, so just use the latest available for this set of partition values.
        Subquery<Integer> subQuery = criteria.subquery(Integer.class);

        // The criteria root is the business object data.
        Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery
                .from(BusinessObjectDataEntity.class);

        // Join to the other tables we can filter on.
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.businessObjectFormat);
        Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> subBusinessObjectDefinitionEntity = subBusinessObjectFormatEntity
                .join(BusinessObjectFormatEntity_.businessObjectDefinition);
        Join<BusinessObjectFormatEntity, FileTypeEntity> subBusinessObjectFormatFileTypeEntity = subBusinessObjectFormatEntity
                .join(BusinessObjectFormatEntity_.fileType);
        Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.status);

        // Create the standard restrictions (i.e. the standard where clauses).
        Predicate subQueryRestriction = builder.equal(subBusinessObjectDefinitionEntity,
                businessObjectDefinitionEntity);
        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage),
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)));
        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(subBusinessObjectFormatFileTypeEntity, fileTypeEntity));

        // Create and add standard restrictions on primary and sub-partition values.
        subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder,
                subBusinessObjectDataEntity, businessObjectDataEntity));

        // Add restrictions on business object data version and business object data status.
        Predicate subQueryRestrictionOnBusinessObjectDataVersionAndStatus = getQueryRestrictionOnBusinessObjectDataVersionAndStatus(
                builder, subBusinessObjectDataEntity, subBusinessObjectDataStatusEntity,
                businessObjectDataKey.getBusinessObjectDataVersion(), businessObjectDataStatus);
        if (subQueryRestrictionOnBusinessObjectDataVersionAndStatus != null) {
            subQueryRestriction = builder.and(subQueryRestriction,
                    subQueryRestrictionOnBusinessObjectDataVersionAndStatus);
        }

        subQuery.select(builder.max(
                subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion)))
                .where(subQueryRestriction);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))
                        .value(subQuery));
    }

    // If a data version was not specified, use the latest one as per specified business object data status.
    if (businessObjectDataKey.getBusinessObjectDataVersion() == null) {
        // Since business object data version is not specified, just use the latest one as per specified business object data status.
        if (businessObjectDataStatus != null) {
            // Business object data version is not specified, so get the latest one as per specified business object data status.
            Subquery<Integer> subQuery = criteria.subquery(Integer.class);

            // The criteria root is the business object data.
            Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery
                    .from(BusinessObjectDataEntity.class);

            // Join to the other tables we can filter on.
            Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity
                    .join(BusinessObjectDataEntity_.status);
            Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity
                    .join(BusinessObjectDataEntity_.businessObjectFormat);

            // Create the standard restrictions (i.e. the standard where clauses).
            Predicate subQueryRestriction = builder.equal(subBusinessObjectFormatEntity,
                    businessObjectFormatEntity);

            // Create and add standard restrictions on primary and sub-partition values.
            subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder,
                    subBusinessObjectDataEntity, businessObjectDataEntity));

            // Create and add standard restrictions on business object data status.
            subQueryRestriction = builder.and(subQueryRestriction, builder.equal(
                    builder.upper(subBusinessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code)),
                    businessObjectDataStatus.toUpperCase()));

            subQuery.select(builder.max(subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.version)))
                    .where(subQueryRestriction);

            mainQueryRestriction = builder.and(mainQueryRestriction, builder
                    .in(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)).value(subQuery));
        } else {
            // Both business object data version and business object data status are not specified, so just use the latest business object data version.
            mainQueryRestriction = builder.and(mainQueryRestriction,
                    builder.equal(businessObjectDataEntity.get(BusinessObjectDataEntity_.latestVersion), true));
        }
    }

    criteria.select(businessObjectDataEntity).where(mainQueryRestriction);

    return executeSingleResultQuery(criteria, String.format(
            "Found more than one business object data instance with parameters {namespace=\"%s\", businessObjectDefinitionName=\"%s\","
                    + " businessObjectFormatUsage=\"%s\", businessObjectFormatFileType=\"%s\", businessObjectFormatVersion=\"%d\","
                    + " businessObjectDataPartitionValue=\"%s\", businessObjectDataSubPartitionValues=\"%s\", businessObjectDataVersion=\"%d\","
                    + " businessObjectDataStatus=\"%s\"}.",
            businessObjectDataKey.getNamespace(), businessObjectDataKey.getBusinessObjectDefinitionName(),
            businessObjectDataKey.getBusinessObjectFormatUsage(),
            businessObjectDataKey.getBusinessObjectFormatFileType(),
            businessObjectDataKey.getBusinessObjectFormatVersion(), businessObjectDataKey.getPartitionValue(),
            CollectionUtils.isEmpty(businessObjectDataKey.getSubPartitionValues()) ? ""
                    : StringUtils.join(businessObjectDataKey.getSubPartitionValues(), ","),
            businessObjectDataKey.getBusinessObjectDataVersion(), businessObjectDataStatus));
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Retrieves a list of business object data entities per specified parameters. This method processes a sublist of partition filters specified by
 * partitionFilterSubListFromIndex and partitionFilterSubListSize parameters.
 *
 * @param businessObjectFormatKey the business object format key (case-insensitive). If a business object format version isn't specified, the latest
 * available format version for each partition value will be used.
 * @param partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of
 * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition
 * values for the relative partitions not to be used for selection passed as nulls.
 * @param businessObjectDataVersion the business object data version. If a business object data version isn't specified, the latest data version based on
 * the specified business object data status is returned.
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified. When
 * business object data version and business object data status both are not specified, the latest data version for each set of partition values will be
 * used regardless of the status./*from  w w  w  .  j  a  va2s . c om*/
 * @param storageName the name of the storage where the business object data storage unit is located (case-insensitive)
 * @param partitionFilterSubListFromIndex the index of the first element in the partition filter sublist
 * @param partitionFilterSubListSize the size of the partition filter sublist
 *
 * @return the list of business object data entities sorted by partition values
 */
private List<BusinessObjectDataEntity> getBusinessObjectDataEntities(
        BusinessObjectFormatKey businessObjectFormatKey, List<List<String>> partitionFilters,
        Integer businessObjectDataVersion, String businessObjectDataStatus, String storageName,
        int partitionFilterSubListFromIndex, int partitionFilterSubListSize) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> businessObjectDataEntity = criteria.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);

    // Create the standard restrictions (i.e. the standard where clauses).

    // Create a standard restriction based on the business object format key values.
    // Please note that we specify not to ignore the business object format version.
    Predicate mainQueryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity,
            businessObjectDefinitionEntity, businessObjectFormatKey, false);

    // If a format version was not specified, use the latest available for this set of partition values.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        // Business object format version is not specified, so just use the latest available for this set of partition values.
        Subquery<Integer> subQuery = criteria.subquery(Integer.class);

        // The criteria root is the business object data.
        Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery
                .from(BusinessObjectDataEntity.class);

        // Join to the other tables we can filter on.
        Join<BusinessObjectDataEntity, StorageUnitEntity> subStorageUnitEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.storageUnits);
        Join<StorageUnitEntity, StorageEntity> subStorageEntity = subStorageUnitEntity
                .join(StorageUnitEntity_.storage);
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.businessObjectFormat);
        Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> subBusinessObjectDefinitionEntity = subBusinessObjectFormatEntity
                .join(BusinessObjectFormatEntity_.businessObjectDefinition);
        Join<BusinessObjectFormatEntity, FileTypeEntity> subBusinessObjectFormatFileTypeEntity = subBusinessObjectFormatEntity
                .join(BusinessObjectFormatEntity_.fileType);
        Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.status);

        // Create the standard restrictions (i.e. the standard where clauses).
        Predicate subQueryRestriction = builder.equal(subBusinessObjectDefinitionEntity,
                businessObjectDefinitionEntity);
        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage),
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)));
        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(subBusinessObjectFormatFileTypeEntity, fileTypeEntity));

        // Create and add standard restrictions on primary and sub-partition values.
        subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder,
                subBusinessObjectDataEntity, businessObjectDataEntity));

        // Add restrictions on business object data version and business object data status.
        Predicate subQueryRestrictionOnBusinessObjectDataVersionAndStatus = getQueryRestrictionOnBusinessObjectDataVersionAndStatus(
                builder, subBusinessObjectDataEntity, subBusinessObjectDataStatusEntity,
                businessObjectDataVersion, businessObjectDataStatus);
        if (subQueryRestrictionOnBusinessObjectDataVersionAndStatus != null) {
            subQueryRestriction = builder.and(subQueryRestriction,
                    subQueryRestrictionOnBusinessObjectDataVersionAndStatus);
        }

        // Create and add a standard restriction on storage.
        subQueryRestriction = builder.and(subQueryRestriction, builder.equal(subStorageEntity, storageEntity));

        subQuery.select(builder.max(
                subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion)))
                .where(subQueryRestriction);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(
                        businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))
                        .value(subQuery));
    }

    // Add restriction as per specified primary and/or sub-partition values.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            getQueryRestrictionOnPartitionValues(builder, businessObjectDataEntity,
                    partitionFilters.subList(partitionFilterSubListFromIndex,
                            partitionFilterSubListFromIndex + partitionFilterSubListSize)));

    // If a data version was specified, use it. Otherwise, use the latest one as per specified business object data status.
    if (businessObjectDataVersion != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.equal(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.version), businessObjectDataVersion));
    } else {
        // Business object data version is not specified, so get the latest one as per specified business object data status, if any.
        // Meaning, when both business object data version and business object data status are not specified, we just return
        // the latest business object data version in the specified storage.
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntity, businessObjectFormatEntity, businessObjectDataStatus, storageEntity);

        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.in(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)).value(subQuery));
    }

    // Add a storage name restriction to the main query where clause.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()));

    // Add the clauses for the query.
    criteria.select(businessObjectDataEntity).where(mainQueryRestriction);

    // Order by partitions.
    List<Order> orderBy = new ArrayList<>();
    for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartition : BUSINESS_OBJECT_DATA_PARTITIONS) {
        orderBy.add(builder.asc(businessObjectDataEntity.get(businessObjectDataPartition)));
    }
    criteria.orderBy(orderBy);

    return entityManager.createQuery(criteria).getResultList();
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Builds a sub-query to select the maximum business object data version.
 *
 * @param builder the criteria builder//ww  w.j a  v  a  2 s .  com
 * @param criteria the criteria query
 * @param businessObjectDataEntity the business object data entity that appears in the from clause of the main query
 * @param businessObjectFormatEntity the business object format entity that appears in the from clause of the main query
 * @param businessObjectDataStatus the business object data status
 *
 * @return the sub-query to select the maximum business object data version
 */
private Subquery<Integer> getMaximumBusinessObjectDataVersionSubQuery(CriteriaBuilder builder,
        CriteriaQuery<?> criteria, From<?, BusinessObjectDataEntity> businessObjectDataEntity,
        From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, String businessObjectDataStatus,
        From<?, StorageEntity> storageEntity) {
    // Business object data version is not specified, so get the latest one in the specified storage.
    Subquery<Integer> subQuery = criteria.subquery(Integer.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> subStorageUnitEntity = subBusinessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> subStorageEntity = subStorageUnitEntity
            .join(StorageUnitEntity_.storage);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);

    // Add a standard restriction on business object format.
    Predicate subQueryRestriction = builder.equal(subBusinessObjectFormatEntity, businessObjectFormatEntity);

    // Create and add standard restrictions on primary and sub-partition values.
    subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder,
            subBusinessObjectDataEntity, businessObjectDataEntity));

    // If specified, create and add a standard restriction on business object data status.
    if (businessObjectDataStatus != null) {
        Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.status);

        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(
                        builder.upper(
                                subBusinessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code)),
                        businessObjectDataStatus.toUpperCase()));
    }

    // Create and add a standard restriction on storage.
    subQueryRestriction = builder.and(subQueryRestriction, builder.equal(subStorageEntity, storageEntity));

    subQuery.select(builder.max(subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.version)))
            .where(subQueryRestriction);

    return subQuery;
}

From source file:org.finra.herd.dao.impl.AbstractHerdDao.java

/**
 * TODO This method may be bdata specific. Consider creating new abstract class to group all bdata related DAO. Builds a sub-query to select the maximum
 * business object data version./*from   w w w.  j a va  2  s.  co  m*/
 *
 * @param builder the criteria builder
 * @param criteria the criteria query
 * @param businessObjectDataEntity the business object data entity that appears in the from clause of the main query
 * @param businessObjectFormatEntity the business object format entity that appears in the from clause of the main query
 * @param businessObjectDataStatus the business object data status
 * @param storageNames the list of storage names where the business object data storage units should be looked for (case-insensitive)
 * @param storagePlatformType the optional storage platform type, e.g. S3 for Hive DDL. It is ignored when the list of storages is not empty
 * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storages is not empty or
 * the storage platform type is specified
 * @param selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status
 *
 * @return the sub-query to select the maximum business object data version
 */
protected Subquery<Integer> getMaximumBusinessObjectDataVersionSubQuery(CriteriaBuilder builder,
        CriteriaQuery<?> criteria, From<?, BusinessObjectDataEntity> businessObjectDataEntity,
        From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, String businessObjectDataStatus,
        List<String> storageNames, String storagePlatformType, String excludedStoragePlatformType,
        boolean selectOnlyAvailableStorageUnits) {
    // Business object data version is not specified, so get the latest one in the specified storage.
    Subquery<Integer> subQuery = criteria.subquery(Integer.class);

    // The criteria root is the business object data.
    Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subQuery.from(BusinessObjectDataEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> subStorageUnitEntity = subBusinessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> subStorageEntity = subStorageUnitEntity
            .join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> subStoragePlatformEntity = subStorageEntity
            .join(StorageEntity_.storagePlatform);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> subBusinessObjectFormatEntity = subBusinessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<StorageUnitEntity, StorageUnitStatusEntity> subStorageUnitStatusEntity = subStorageUnitEntity
            .join(StorageUnitEntity_.status);

    // Add a standard restriction on business object format.
    Predicate subQueryRestriction = builder.equal(subBusinessObjectFormatEntity, businessObjectFormatEntity);

    // Create and add standard restrictions on primary and sub-partition values.
    subQueryRestriction = builder.and(subQueryRestriction, getQueryRestrictionOnPartitionValues(builder,
            subBusinessObjectDataEntity, businessObjectDataEntity));

    // If specified, create and add a standard restriction on business object data status.
    if (businessObjectDataStatus != null) {
        Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> subBusinessObjectDataStatusEntity = subBusinessObjectDataEntity
                .join(BusinessObjectDataEntity_.status);

        subQueryRestriction = builder.and(subQueryRestriction,
                builder.equal(
                        builder.upper(
                                subBusinessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code)),
                        businessObjectDataStatus.toUpperCase()));
    }

    // Create and add a standard restriction on storage.
    subQueryRestriction = builder.and(subQueryRestriction,
            getQueryRestrictionOnStorage(builder, subStorageEntity, subStoragePlatformEntity, storageNames,
                    storagePlatformType, excludedStoragePlatformType));

    // If specified, add a restriction on storage unit status availability flag.
    if (selectOnlyAvailableStorageUnits) {
        subQueryRestriction = builder.and(subQueryRestriction,
                builder.isTrue(subStorageUnitStatusEntity.get(StorageUnitStatusEntity_.available)));
    }

    subQuery.select(builder.max(subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.version)))
            .where(subQueryRestriction);

    return subQuery;
}