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:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java

@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);
        }//from w ww  .ja v  a2  s .c om

        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.herd.dao.impl.BusinessObjectDataDaoImpl.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 . ja v a  2  s. co  m*/
 * @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,
                Collections.singletonList(storageName), null, null, false);

        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.herd.dao.impl.BusinessObjectDataDaoImpl.java

/**
 * Creates a sub query for the maximum business object data version.
 *
 * @param builder criteria builder/*from  w w w .j av  a2 s .co m*/
 * @param criteria criteria query
 * @param businessObjectDataEntity business object data entity
 * @param businessObjectFormatEntity business object format entity
 * @param businessObjectDataStatus business object status, case insensitive
 *
 * @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) {
    // Create a sub query for the business object data version.
    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);

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

    // Add all clauses to the sub query.
    subQuery.select(builder.max(subBusinessObjectDataEntity.get(BusinessObjectDataEntity_.version)))
            .where(subQueryRestriction);

    return subQuery;
}

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

/**
 * {@inheritDoc}/*from w  w  w.  j  ava  2 s  . c  o m*/
 */
@Override
public Map<BusinessObjectDataEntity, StoragePolicyEntity> getBusinessObjectDataEntitiesMatchingStoragePolicies(
        StoragePolicyPriorityLevel storagePolicyPriorityLevel, List<String> supportedBusinessObjectDataStatuses,
        int startPosition, int maxResult) {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.status);
    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 main query restrictions based on the specified parameters.
    List<Predicate> mainQueryPredicates = new ArrayList<>();

    // Add a restriction on business object definition.
    mainQueryPredicates.add(storagePolicyPriorityLevel.isBusinessObjectDefinitionIsNull()
            ? builder.isNull(storagePolicyEntity.get(StoragePolicyEntity_.businessObjectDefinition))
            : builder.equal(businessObjectDefinitionEntity,
                    storagePolicyEntity.get(StoragePolicyEntity_.businessObjectDefinition)));

    // Add a restriction on business object format usage.
    mainQueryPredicates.add(storagePolicyPriorityLevel.isUsageIsNull()
            ? builder.isNull(storagePolicyEntity.get(StoragePolicyEntity_.usage))
            : builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
                    builder.upper(storagePolicyEntity.get(StoragePolicyEntity_.usage))));

    // Add a restriction on business object format file type.
    mainQueryPredicates.add(storagePolicyPriorityLevel.isFileTypeIsNull()
            ? builder.isNull(storagePolicyEntity.get(StoragePolicyEntity_.fileType))
            : builder.equal(fileTypeEntity, storagePolicyEntity.get(StoragePolicyEntity_.fileType)));

    // Add a restriction on storage policy filter storage.
    mainQueryPredicates.add(builder.equal(storageUnitEntity.get(StorageUnitEntity_.storage),
            storagePolicyEntity.get(StoragePolicyEntity_.storage)));

    // Add a restriction on supported business object data statuses.
    mainQueryPredicates.add(businessObjectDataStatusEntity.get(BusinessObjectDataStatusEntity_.code)
            .in(supportedBusinessObjectDataStatuses));

    // Build a subquery to eliminate business object data instances that already have storage unit in the storage policy destination storage.
    Subquery<BusinessObjectDataEntity> subquery = criteria.subquery(BusinessObjectDataEntity.class);
    Root<BusinessObjectDataEntity> subBusinessObjectDataEntity = subquery.from(BusinessObjectDataEntity.class);
    subquery.select(subBusinessObjectDataEntity);

    // Join to the other tables we can filter on for the subquery.
    Join<BusinessObjectDataEntity, StorageUnitEntity> subStorageUnitEntity = subBusinessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);

    // Create the subquery restrictions based on the main query and storage policy destination storage.
    List<Predicate> subQueryPredicates = new ArrayList<>();
    subQueryPredicates.add(builder.equal(subBusinessObjectDataEntity, businessObjectDataEntity));
    subQueryPredicates.add(builder.equal(subStorageUnitEntity.get(StorageUnitEntity_.storage),
            storagePolicyEntity.get(StoragePolicyEntity_.destinationStorage)));

    // Add all clauses to the subquery.
    subquery.select(subBusinessObjectDataEntity).where(subQueryPredicates.toArray(new Predicate[] {}));

    // Add a main query restriction based on the subquery to eliminate business object data
    // instances that already have storage unit in the storage policy destination storage.
    mainQueryPredicates.add(builder.not(builder.exists(subquery)));

    // Order the results by business object data "created on" value.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn));

    // Add the select clause to the main query.
    criteria.multiselect(businessObjectDataEntity, storagePolicyEntity);

    // Add the where clause to the main query.
    criteria.where(mainQueryPredicates.toArray(new Predicate[] {}));

    // Add the order by clause to the main query.
    criteria.orderBy(orderByCreatedOn);

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).setFirstResult(startPosition)
            .setMaxResults(maxResult).getResultList();

    // Populate the result map from the returned tuples (i.e. 1 tuple for each row).
    Map<BusinessObjectDataEntity, StoragePolicyEntity> result = new LinkedHashMap<>();
    for (Tuple tuple : tuples) {
        // Since multiple storage policies can contain identical filters, we add the below check to select each business object data instance only once.
        if (!result.containsKey(tuple.get(businessObjectDataEntity))) {
            result.put(tuple.get(businessObjectDataEntity), tuple.get(storagePolicyEntity));
        }
    }

    return result;
}

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

/**
 * Builds a sub-query to select the maximum business object data version.
 *
 * @param builder the criteria builder//from  w  ww. 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 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, From<?, StorageEntity> storageEntity,
        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<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, builder.equal(subStorageEntity, storageEntity));

    // 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.finra.herd.dao.impl.StorageUnitDaoImpl.java

/**
 * Builds a sub-query to select the maximum business object data version.
 *
 * @param builder the criteria builder//from   ww w. j av  a  2  s  .c  om
 * @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) {//from   ww w. jav a  2 s .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 v a 2s.  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));
    }// w  w w .j av  a 2 s  . c o  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;
}