Example usage for javax.persistence.criteria Subquery select

List of usage examples for javax.persistence.criteria Subquery select

Introduction

In this page you can find the example usage for javax.persistence.criteria Subquery select.

Prototype

Subquery<T> select(Expression<T> expression);

Source Link

Document

Specify the item that is to be returned as the subquery result.

Usage

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

/**
 * Builds a sub-query to select the maximum business object data version.
 *
 * @param builder the criteria builder//from w w  w  . j av  a2  s .c o m
 * @param criteria the criteria query
 * @param businessObjectDefinitionEntity the business object definition 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 fileTypeEntity the file type entity that appears in the from clause of the main query
 * @param businessObjectDataEntity the business object data entity that appears in the from clause of the main query
 * @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
 * @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
 */
private Subquery<Integer> getMaximumBusinessObjectFormatVersionSubQuery(CriteriaBuilder builder,
        CriteriaQuery<?> criteria, From<?, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity,
        From<?, BusinessObjectFormatEntity> businessObjectFormatEntity, From<?, FileTypeEntity> fileTypeEntity,
        From<?, BusinessObjectDataEntity> businessObjectDataEntity, Integer businessObjectDataVersion,
        String businessObjectDataStatus, List<String> storageNames, String storagePlatformType,
        String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits) {
    // 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<StorageEntity, StoragePlatformEntity> subStoragePlatformEntity = subStorageEntity
            .join(StorageEntity_.storagePlatform);
    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);
    Join<StorageUnitEntity, StorageUnitStatusEntity> subStorageUnitStatusEntity = subStorageUnitEntity
            .join(StorageUnitEntity_.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,
            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)));
    }

    // Add all of the clauses to the subquery.
    subQuery.select(builder
            .max(subBusinessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion)))
            .where(subQueryRestriction);

    return subQuery;
}

From source file:org.jgrades.admin.accounts.UserSpecificationsImpl.java

private static Predicate getSearchPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb,
        Class clazz) {/*ww w .j av  a2s.c o  m*/
    Subquery subquery = cq.subquery(clazz);
    Root subRoot = subquery.from(clazz);
    subquery.select(subRoot);
    Predicate predicate = cb.equal(subRoot.get("id"), root.get("id"));
    subquery.where(predicate);
    return cb.exists(subquery);
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private Subquery<RuleResponsibilityBo> addResponsibilityCriteria(CriteriaQuery<RuleBaseValues> query,
        Collection<String> workgroupIds, String workflowId, Collection actionRequestCodes, Boolean searchUser,
        Boolean searchUserInWorkgroups) {

    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);

    List<javax.persistence.criteria.Predicate> respPredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> ruleRespNamePredicates = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> userNamePreds = new ArrayList<javax.persistence.criteria.Predicate>();

    List<javax.persistence.criteria.Predicate> workgroupPreds = new ArrayList<javax.persistence.criteria.Predicate>();

    if ((actionRequestCodes != null) && (!actionRequestCodes.isEmpty())) {
        Expression<String> exp = fromResp.get("actionRequestedCd");
        javax.persistence.criteria.Predicate actionRequestPredicate = exp.in(actionRequestCodes);

        respPredicates.add(actionRequestPredicate);
    }//from w ww. j a  va2s.c o  m

    if (!org.apache.commons.lang.StringUtils.isEmpty(workflowId)) {
        // workflow user id exists
        if (searchUser != null && searchUser) {
            // searching user wishes to search for rules specific to user
            userNamePreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workflowId));
            userNamePreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_WORKFLOW_ID));

            javax.persistence.criteria.Predicate[] preds = userNamePreds
                    .toArray(new javax.persistence.criteria.Predicate[userNamePreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));

        }
        if ((searchUserInWorkgroups != null && searchUserInWorkgroups) && (workgroupIds != null)
                && (!workgroupIds.isEmpty())) {
            // at least one workgroup id exists and user wishes to search on workgroups

            Expression<String> exp = fromResp.get("ruleResponsibilityName");
            javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
            workgroupPreds.add(groupIdPredicate);
            workgroupPreds.add(cb.equal(fromResp.get("ruleResponsibilityType"),
                    KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
            javax.persistence.criteria.Predicate[] preds = workgroupPreds
                    .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
            ruleRespNamePredicates.add(cb.and(preds));
        }
    } else if ((workgroupIds != null) && (workgroupIds.size() == 1)) {
        // no user and one workgroup id
        workgroupPreds.add(cb.like(fromResp.get("ruleResponsibilityName"), workgroupIds.iterator().next()));
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));

    } else if ((workgroupIds != null) && (workgroupIds.size() > 1)) {
        // no user and more than one workgroup id

        Expression<String> exp = fromResp.get("ruleResponsibilityName");
        javax.persistence.criteria.Predicate groupIdPredicate = exp.in(workgroupIds);
        workgroupPreds.add(
                cb.equal(fromResp.get("ruleResponsibilityType"), KewApiConstants.RULE_RESPONSIBILITY_GROUP_ID));
        javax.persistence.criteria.Predicate[] preds = workgroupPreds
                .toArray(new javax.persistence.criteria.Predicate[workgroupPreds.size()]);
        ruleRespNamePredicates.add(cb.and(preds));
    }

    if (!ruleRespNamePredicates.isEmpty()) {
        javax.persistence.criteria.Predicate[] preds = ruleRespNamePredicates
                .toArray(new javax.persistence.criteria.Predicate[ruleRespNamePredicates.size()]);
        respPredicates.add(cb.or(preds));
    }

    if (!respPredicates.isEmpty()) {

        javax.persistence.criteria.Predicate[] preds = respPredicates
                .toArray(new javax.persistence.criteria.Predicate[respPredicates.size()]);
        subquery.where(preds);
        subquery.select(fromResp.get("ruleBaseValuesId"));
        return subquery;
    }
    return null;
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private List<javax.persistence.criteria.Predicate> getSearchCriteria(Root<RuleBaseValues> root,
        CriteriaQuery<RuleBaseValues> query, String docTypeName, String ruleTemplateId, String ruleDescription,
        Boolean delegateRule, Boolean activeInd, Map extensionValues) {
    List<javax.persistence.criteria.Predicate> predicates = new ArrayList<javax.persistence.criteria.Predicate>();
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();

    predicates.add(cb.equal(root.get("currentInd"), Boolean.TRUE));
    predicates.add(cb.equal(root.get("templateRuleInd"), Boolean.FALSE));
    if (activeInd != null) {
        predicates.add(cb.equal(root.get("active"), activeInd));
    }//from  w  ww. j  a  v  a2 s .  co  m
    if (docTypeName != null) {
        predicates.add(cb.like(cb.upper(root.<String>get("docTypeName")), docTypeName.toUpperCase()));
    }
    if (ruleDescription != null && !ruleDescription.trim().equals("")) {
        predicates.add(cb.like(cb.upper(root.<String>get("description")), ruleDescription.toUpperCase()));
    }
    if (ruleTemplateId != null) {
        predicates.add(cb.equal(root.get("ruleTemplateId"), ruleTemplateId));
    }
    if (delegateRule != null) {
        predicates.add(cb.equal(root.get("delegateRule"), delegateRule));
    }
    if (extensionValues != null && !extensionValues.isEmpty()) {
        for (Iterator iter2 = extensionValues.entrySet().iterator(); iter2.hasNext();) {
            Map.Entry entry = (Map.Entry) iter2.next();
            if (!StringUtils.isEmpty((String) entry.getValue())) {
                Subquery ruleExtSubQuery = query.subquery(RuleExtensionBo.class);
                Root<RuleExtensionBo> ruleExtRoot = ruleExtSubQuery.from(RuleExtensionBo.class);
                javax.persistence.criteria.Predicate predAnd = cb.and(
                        cb.equal(ruleExtRoot.get("extensionValues").get("key"), entry.getKey()),
                        cb.like(ruleExtRoot.get("extensionValues").<String>get("value"),
                                ("%" + (String) entry.getValue() + "%").toUpperCase()));
                ruleExtSubQuery.where(predAnd);
                ruleExtSubQuery.select(ruleExtRoot.get("ruleBaseValuesId"));

                predicates.add(cb.in(root.get("id")).value(ruleExtSubQuery));
            }
        }
    }
    return predicates;
}

From source file:org.kuali.rice.kew.rule.dao.impl.RuleDAOJpa.java

private Subquery<RuleResponsibilityBo> getRuleResponsibilitySubQuery(String ruleRespName,
        CriteriaQuery<RuleBaseValues> query) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    Subquery<RuleResponsibilityBo> subquery = query.subquery(RuleResponsibilityBo.class);
    Root fromResp = subquery.from(RuleResponsibilityBo.class);
    subquery.where(cb.equal(fromResp.get("ruleResponsibilityName"), ruleRespName));
    subquery.select(fromResp.get("ruleBaseValuesId"));

    return subquery;
}

From source file:org.seedstack.i18n.rest.internal.infrastructure.jpa.KeysQuery.java

private Subquery<String> getAllKeysWithTranslationFor(String locale) {
    Subquery<String> subQuery;
    if (selectQuery != null) {
        subQuery = selectQuery.subquery(String.class);
    } else {/*from w w w . j a va2  s.  co m*/
        subQuery = countQuery.subquery(String.class);
    }
    Root<Key> fromKey = subQuery.from(Key.class);

    subQuery.select(fromKey.get(ENTITY_ID));

    Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);

    Predicate keyIdsAreEquals = criteriaBuilder.equal(join.get(ENTITY_ID).get(LOCALE), locale);
    Predicate translationIsPresent = criteriaBuilder.notEqual(join.get(TRANSLATION_VALUE), "");

    subQuery.where(criteriaBuilder.and(keyIdsAreEquals, translationIsPresent));
    return subQuery;
}

From source file:org.seedstack.i18n.rest.internal.KeyJpaFinder.java

/**
 * Extracts predicates from criteria.//  w  ww  . j  av a2 s  . co m
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }
        // is the key outdated
        if (isOutdated != null) {
            predicates.add(cb.equal(k.<Boolean>get(OUTDATED), isOutdated));
        }

        // if a default translation is available
        String defaultLocale = localeService.getDefaultLocale();
        if (defaultLocale != null && isApprox != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), defaultLocale));

            // is the translation approximate
            predicates.add(cb.equal(tln.get(APPROXIMATE), isApprox));
        }

        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), defaultLocale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}

From source file:org.seedstack.i18n.rest.internal.TranslationJpaFinder.java

/**
 * Extracts predicates from criteria./*from   ww  w .j a va 2  s  .  com*/
 *
 * @param criteria criteria
 * @param cb       criteria builder
 * @param k        root key
 * @return list of predicate
 */
private Predicate[] getPredicates(Map<String, Object> criteria, CriteriaQuery q, CriteriaBuilder cb,
        Root<Key> k) {
    List<Predicate> predicates = new ArrayList<Predicate>();
    if (criteria != null) {
        // extract criteria from the map
        Boolean isApprox = (Boolean) criteria.get(IS_APPROX);
        Boolean isMissing = (Boolean) criteria.get(IS_MISSING);
        Boolean isOutdated = (Boolean) criteria.get(IS_OUTDATED);
        String searchName = (String) criteria.get(SEARCH_NAME);
        String locale = (String) criteria.get(LOCALE);

        // is the key LIKE searchName
        if (StringUtils.isNotBlank(searchName)) {
            predicates.add(cb.like(k.<String>get(ENTITY_ID), "%" + searchName + "%"));
        }

        // if a default translation is available
        if (isApprox != null || isOutdated != null) {
            // join translation table
            Join<Key, Translation> tln = k.join(TRANSLATIONS, JoinType.LEFT);
            // WHERE locale = default locale
            predicates.add(cb.equal(tln.get(ENTITY_ID).get(LOCALE), locale));

            // is the key outdated
            if (isOutdated != null) {
                predicates.add(cb.equal(tln.<Boolean>get(OUTDATED), isOutdated));
            }

            // is the translation approximate
            if (isApprox != null) {
                predicates.add(cb.equal(tln.<Boolean>get(APPROXIMATE), isApprox));
            }
        }
        // is the translation missing
        if (isMissing != null) {
            // SubQuery to find all the key which get a translation for the default locale
            //noinspection unchecked
            Subquery<String> subquery = q.subquery(String.class);
            Root<Key> fromKey = subquery.from(Key.class);
            subquery.select(fromKey.<String>get(ENTITY_ID));
            Join join = fromKey.join(TRANSLATIONS, JoinType.LEFT);
            subquery.where(cb.and(cb.equal(join.get(ENTITY_ID).get(LOCALE), locale),
                    cb.notEqual(join.get(VALUE), "")));
            // Find all keys not in the above subquery, ie. all the keys missing
            predicates.add(cb.not(cb.in(k.get(ENTITY_ID)).value(subquery)));
        }
    }
    return predicates.toArray(new Predicate[predicates.size()]);
}