Example usage for javax.persistence.criteria CriteriaBuilder isTrue

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

Introduction

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

Prototype

Predicate isTrue(Expression<Boolean> x);

Source Link

Document

Create a predicate testing for a true value.

Usage

From source file:com.deloitte.smt.service.SignalDetectionService.java

/**
 * @param searchDto/*w  w  w  . ja va  2  s  .  c o m*/
 * @param criteriaBuilder
 * @param criteriaQuery
 * @param rootSignalDetection
 * @param predicates
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addSocs(SearchDto searchDto, CriteriaBuilder criteriaBuilder, CriteriaQuery criteriaQuery,
        Root<SignalDetection> rootSignalDetection, List<Predicate> predicates) {
    if (!CollectionUtils.isEmpty(searchDto.getSocs())) {
        Root<Soc> rootSoc = criteriaQuery.from(Soc.class);
        Predicate signalDetectionSocEquals = criteriaBuilder.equal(rootSignalDetection.get("id"),
                rootSoc.get(SmtConstant.DETECTION_ID.getDescription()));

        Predicate socNameIn = criteriaBuilder.isTrue(rootSoc.get("socName").in(searchDto.getSocs()));

        predicates.add(signalDetectionSocEquals);
        predicates.add(socNameIn);
    }
}

From source file:com.deloitte.smt.service.SignalDetectionService.java

/**
 * @param searchDto/*from  ww  w  . j  ava  2 s . c  om*/
 * @param criteriaBuilder
 * @param criteriaQuery
 * @param rootSignalDetection
 * @param predicates
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addHlgts(SearchDto searchDto, CriteriaBuilder criteriaBuilder, CriteriaQuery criteriaQuery,
        Root<SignalDetection> rootSignalDetection, List<Predicate> predicates) {
    if (!CollectionUtils.isEmpty(searchDto.getHlgts())) {
        Root<Hlgt> rootHlgt = criteriaQuery.from(Hlgt.class);
        Predicate signalDetectionHlgtEquals = criteriaBuilder.equal(rootSignalDetection.get("id"),
                rootHlgt.get(SmtConstant.DETECTION_ID.getDescription()));

        Predicate hlgtNameIn = criteriaBuilder.isTrue(rootHlgt.get("hlgtName").in(searchDto.getHlgts()));

        predicates.add(signalDetectionHlgtEquals);
        predicates.add(hlgtNameIn);
    }
}

From source file:org.openlmis.migration.tool.openlmis.referencedata.repository.custom.impl.OlmisFacilityTypeApprovedProductRepositoryImpl.java

@Override
public Collection<FacilityTypeApprovedProduct> searchProducts(UUID facilityId, UUID programId,
        boolean fullSupply) {
    checkNotNull(facilityId);//w  w w.  java2  s  .  c o  m

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();

    CriteriaQuery<FacilityTypeApprovedProduct> query = builder.createQuery(FacilityTypeApprovedProduct.class);

    Root<FacilityTypeApprovedProduct> ftap = query.from(FacilityTypeApprovedProduct.class);
    Root<Facility> facility = query.from(Facility.class);

    Join<Facility, FacilityType> fft = facility.join("type");

    Join<FacilityTypeApprovedProduct, FacilityType> ft = ftap.join("facilityType");
    Join<FacilityTypeApprovedProduct, ProgramOrderable> pp = ftap.join("programOrderable");

    Join<ProgramOrderable, Program> program = pp.join("program");

    Predicate conjunction = builder.conjunction();
    if (programId != null) {
        conjunction = builder.and(conjunction, builder.equal(program.get("id"), programId));
    }
    conjunction = builder.and(conjunction, builder.equal(fft.get("id"), ft.get("id")));
    conjunction = builder.and(conjunction, builder.equal(facility.get("id"), facilityId));
    conjunction = builder.and(conjunction, builder.equal(pp.get("fullSupply"), fullSupply));
    conjunction = builder.and(conjunction, builder.isTrue(pp.get("active")));

    query.select(ftap);
    query.where(conjunction);

    Join<ProgramOrderable, OrderableDisplayCategory> category = pp.join("orderableDisplayCategory");
    Join<ProgramOrderable, Orderable> orderable = pp.join("product");

    query.orderBy(builder.asc(category.get("orderedDisplayValue").get("displayOrder")),
            builder.asc(category.get("orderedDisplayValue").get("displayName")),
            builder.asc(orderable.get("productCode")));

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

From source file:com.deloitte.smt.service.SignalDetectionService.java

/**
 * /*w ww.java  2  s  . c o m*/
 * @param searchDto
 * @param criteriaBuilder
 * @param query
 * @param rootTopic
 * @param predicates
 */
private void addUserGroupKeys(SearchDto searchDto, CriteriaBuilder criteriaBuilder,
        Join<SignalDetection, TopicSignalDetectionAssignmentAssignees> joinDetectionAssignees,
        Root<SignalDetection> rootSignalDetection, List<Predicate> predicates) {

    if (!CollectionUtils.isEmpty(searchDto.getUserKeys())
            && !CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && !CollectionUtils.isEmpty(searchDto.getOwners())) {

        predicates.add(criteriaBuilder.or(
                criteriaBuilder.isTrue(joinDetectionAssignees.get("userKey").in(searchDto.getUserKeys())),
                criteriaBuilder.or(
                        criteriaBuilder.isTrue(
                                joinDetectionAssignees.get("userGroupKey").in(searchDto.getUserGroupKeys())),
                        criteriaBuilder.isTrue(rootSignalDetection.get("owner").in(searchDto.getOwners())))));

    } else if (!CollectionUtils.isEmpty(searchDto.getUserKeys())
            && !CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && CollectionUtils.isEmpty(searchDto.getOwners())) {
        predicates.add(criteriaBuilder.or(
                criteriaBuilder.isTrue(joinDetectionAssignees.get("userKey").in(searchDto.getUserKeys())),
                criteriaBuilder
                        .isTrue(joinDetectionAssignees.get("userGroupKey").in(searchDto.getUserGroupKeys()))));
    } else if (!CollectionUtils.isEmpty(searchDto.getUserKeys())
            && CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && CollectionUtils.isEmpty(searchDto.getOwners())) {
        predicates.add(criteriaBuilder
                .or(criteriaBuilder.isTrue(joinDetectionAssignees.get("userKey").in(searchDto.getUserKeys()))));

    } else if (!CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && CollectionUtils.isEmpty(searchDto.getUserKeys())
            && CollectionUtils.isEmpty(searchDto.getOwners())) {
        predicates.add(criteriaBuilder.or(criteriaBuilder
                .isTrue(joinDetectionAssignees.get("userGroupKey").in(searchDto.getUserGroupKeys()))));

    } else if (!CollectionUtils.isEmpty(searchDto.getOwners())
            && CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && CollectionUtils.isEmpty(searchDto.getUserKeys())) {
        predicates.add(criteriaBuilder.or(
                criteriaBuilder.isTrue(
                        rootSignalDetection.get(SmtConstant.OWNER.getDescription()).in(searchDto.getOwners())),
                criteriaBuilder.isTrue(rootSignalDetection.get(SmtConstant.OWNER.getDescription()).isNull())));

    } else if (!CollectionUtils.isEmpty(searchDto.getUserKeys())
            && !CollectionUtils.isEmpty(searchDto.getOwners())
            && CollectionUtils.isEmpty(searchDto.getUserGroupKeys())) {
        predicates.add(criteriaBuilder.or(
                criteriaBuilder.isTrue(joinDetectionAssignees.get("userKey").in(searchDto.getUserKeys())),
                criteriaBuilder.isTrue(rootSignalDetection.get(SmtConstant.OWNER.getDescription())
                        .in(searchDto.getOwners()))));
    } else if (!CollectionUtils.isEmpty(searchDto.getUserGroupKeys())
            && !CollectionUtils.isEmpty(searchDto.getOwners())
            && CollectionUtils.isEmpty(searchDto.getUserKeys())) {
        predicates.add(criteriaBuilder.or(
                criteriaBuilder
                        .isTrue(joinDetectionAssignees.get("userGroupKey").in(searchDto.getUserGroupKeys())),
                criteriaBuilder.isTrue(rootSignalDetection.get(SmtConstant.OWNER.getDescription())
                        .in(searchDto.getOwners()))));
    }

}

From source file:com.faceye.feature.repository.jpa.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override/*  w  w  w  .  j a va2  s.co m*/
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (CollectionUtils.isNotEmpty(filters)) {

                List<Predicate> predicates = Lists.newArrayList();
                for (SearchFilter filter : filters) {
                    // nested path translate, Task??"user.name"filedName, ?Task.user.name
                    String[] names = StringUtils.split(filter.fieldName, ".");
                    Path expression = root.get(names[0]);
                    for (int i = 1; i < names.length; i++) {
                        expression = expression.get(names[i]);
                    }

                    // logic operator
                    switch (filter.operator) {
                    case EQ:
                        if (filter.value instanceof Number) {
                            predicates.add(builder.equal(expression, (Number) filter.value));
                        } else if (filter.value instanceof String) {
                            if (StringUtils.isNotEmpty(filter.value.toString())) {
                                predicates.add(builder.equal(expression, filter.value));
                            }
                        } else {
                            predicates.add(builder.equal(expression, filter.value));
                        }
                        break;
                    case LIKE:
                        predicates.add(builder.like(expression, "%" + filter.value + "%"));
                        break;
                    case GT:
                        predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                        break;
                    case LT:
                        predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                        break;
                    case GTE:
                        predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case LTE:
                        predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                        break;
                    case ISTRUE:
                        predicates.add(builder.isTrue(expression));
                        break;
                    case ISFALSE:
                        predicates.add(builder.isFalse(expression));
                        break;
                    case ISEMPTY:
                        predicates.add(builder.isEmpty(expression));
                        break;
                    case ISNULL:
                        predicates.add(builder.isNull(expression));
                        break;
                    case NE:
                        predicates.add(builder.notEqual(expression, filter.value));
                    }
                }

                // ? and ???
                if (!predicates.isEmpty()) {
                    return builder.and(predicates.toArray(new Predicate[predicates.size()]));
                }
            }

            return builder.conjunction();
        }
    };
}

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

/**
 * {@inheritDoc}/*from   ww w .java 2 s  . c om*/
 */
@Override
public BusinessObjectDefinitionEntity getLegacyBusinessObjectDefinitionByName(
        String businessObjectDefinitionName) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionEntity> criteria = builder
            .createQuery(BusinessObjectDefinitionEntity.class);

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(
            builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
            businessObjectDefinitionName.toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.isTrue(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.legacy)));

    criteria.select(businessObjectDefinitionEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria, String.format(
            "Found more than one business object definition with parameters {businessObjectDefinitionName=\"%s\", legacy=\"Y\"}.",
            businessObjectDefinitionName));
}

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

/**
 * {@inheritDoc}//  w  ww  .jav  a2  s . c o  m
 */
@Override
public BusinessObjectFormatEntity getBusinessObjectFormatByAltKey(
        BusinessObjectFormatKey businessObjectFormatKey) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectFormatEntity> criteria = builder.createQuery(BusinessObjectFormatEntity.class);

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    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).
    // Please note that we specify not to ignore the business object format version.
    Predicate queryRestriction = getQueryRestriction(builder, businessObjectFormatEntity, fileTypeEntity,
            businessObjectDefinitionEntity, businessObjectFormatKey, false);

    // If a business format version was not specified, use the latest one.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        queryRestriction = builder.and(queryRestriction,
                builder.isTrue(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.latestVersion)));
    }

    criteria.select(businessObjectFormatEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria,
            String.format("Found more than one business object format instance with parameters "
                    + "{namespace=\"%s\", businessObjectDefinitionName=\"%s\", businessObjectFormatUsage=\"%s\", businessObjectFormatFileType=\"%s\", "
                    + "businessObjectFormatVersion=\"%d\"}.", businessObjectFormatKey.getNamespace(),
                    businessObjectFormatKey.getBusinessObjectDefinitionName(),
                    businessObjectFormatKey.getBusinessObjectFormatUsage(),
                    businessObjectFormatKey.getBusinessObjectFormatFileType(),
                    businessObjectFormatKey.getBusinessObjectFormatVersion()));
}

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  www  .j  a  v  a  2s.  c om
 *
 * @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;
}

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

@Override
public Map<BusinessObjectDataEntity, StoragePolicyEntity> getBusinessObjectDataEntitiesMatchingStoragePolicies(
        StoragePolicyPriorityLevel storagePolicyPriorityLevel, List<String> supportedBusinessObjectDataStatuses,
        int storagePolicyTransitionMaxAllowedAttempts, 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 along with the storage policy.
    Root<BusinessObjectDataEntity> businessObjectDataEntityRoot = criteria.from(BusinessObjectDataEntity.class);
    Root<StoragePolicyEntity> storagePolicyEntityRoot = criteria.from(StoragePolicyEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.businessObjectFormat);

    // Create main query restrictions based on the specified parameters.
    List<Predicate> predicates = new ArrayList<>();

    // Add restriction on business object definition.
    predicates.add(storagePolicyPriorityLevel.isBusinessObjectDefinitionIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId))
            : builder.equal(/*from ww  w  .  ja  va2 s  .  c o m*/
                    businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.businessObjectDefinitionId),
                    storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId)));

    // Add restriction on business object format usage.
    predicates.add(storagePolicyPriorityLevel.isUsageIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage))
            : builder.equal(
                    builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                    builder.upper(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage))));

    // Add restriction on business object format file type.
    predicates.add(storagePolicyPriorityLevel.isFileTypeIsNull()
            ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.fileType))
            : builder.equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileTypeCode),
                    storagePolicyEntityRoot.get(StoragePolicyEntity_.fileTypeCode)));

    // Add restriction on storage policy filter storage.
    predicates.add(builder.equal(storageUnitEntityJoin.get(StorageUnitEntity_.storageName),
            storagePolicyEntityRoot.get(StoragePolicyEntity_.storageName)));

    // Add restriction on storage policy latest version flag.
    predicates.add(builder.isTrue(storagePolicyEntityRoot.get(StoragePolicyEntity_.latestVersion)));

    // Add restriction on storage policy status.
    predicates.add(builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.statusCode),
            StoragePolicyStatusEntity.ENABLED));

    // Add restriction on supported business object data statuses.
    predicates.add(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.statusCode)
            .in(supportedBusinessObjectDataStatuses));

    // Add restrictions as per storage policy transition type.
    predicates.add(
            builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.storagePolicyTransitionTypeCode),
                    StoragePolicyTransitionTypeEntity.GLACIER));
    predicates.add(storageUnitEntityJoin.get(StorageUnitEntity_.statusCode)
            .in(Lists.newArrayList(StorageUnitStatusEntity.ENABLED, StorageUnitStatusEntity.ARCHIVING)));

    // If specified, add restriction on maximum allowed attempts for a storage policy transition.
    if (storagePolicyTransitionMaxAllowedAttempts > 0) {
        predicates.add(builder.or(
                builder.isNull(
                        storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts)),
                builder.lessThan(
                        storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts),
                        storagePolicyTransitionMaxAllowedAttempts)));
    }

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

    // Add the select clause to the main query.
    criteria.multiselect(businessObjectDataEntityRoot, storagePolicyEntityRoot);

    // Add the where clause to the main query.
    criteria.where(predicates.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(businessObjectDataEntityRoot))) {
            result.put(tuple.get(businessObjectDataEntityRoot), tuple.get(storagePolicyEntityRoot));
        }
    }

    return result;
}

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

/**
 * Retrieves partition value per specified parameters that includes the aggregate function.
 * <p>//w w w .j  av a2s .  co  m
 * Returns null if the business object format key does not exist.
 *
 * @param partitionColumnPosition the partition column position (1-based numbering)
 * @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 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 will be used for each partition value.
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified.
 * @param storageNames the optional list of storage names (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 aggregateFunction the aggregate function to use against partition values
 * @param upperBoundPartitionValue the optional inclusive upper bound for the maximum available partition value
 * @param lowerBoundPartitionValue the optional inclusive lower bound for the maximum available partition value
 *
 * @return the partition value
 */
private String getBusinessObjectDataPartitionValue(int partitionColumnPosition,
        final BusinessObjectFormatKey businessObjectFormatKey, final Integer businessObjectDataVersion,
        String businessObjectDataStatus, List<String> storageNames, String storagePlatformType,
        String excludedStoragePlatformType, final AggregateFunction aggregateFunction,
        String upperBoundPartitionValue, String lowerBoundPartitionValue) {
    // We cannot use businessObjectFormatKey passed in since it is case-insensitive. Case-insensitive values requires upper() function in the SQL query, and
    // it has caused performance problems. So we need to extract case-sensitive business object format key from database so we can eliminate the upper()
    // function.
    BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectFormatDao
            .getBusinessObjectFormatByAltKey(businessObjectFormatKey);

    BusinessObjectFormatKey businessObjectFormatKeyCaseSensitive = (BusinessObjectFormatKey) businessObjectFormatKey
            .clone();
    if (businessObjectFormatEntity == null) {
        // Returns null if business object format key does not exist.
        return null;
    } else {
        // Sets the exact values for business object format key from the database. Note that usage type is still case-insensitive.
        businessObjectFormatKeyCaseSensitive.setNamespace(
                businessObjectFormatEntity.getBusinessObjectDefinition().getNamespace().getCode());
        businessObjectFormatKeyCaseSensitive.setBusinessObjectDefinitionName(
                businessObjectFormatEntity.getBusinessObjectDefinition().getName());
        businessObjectFormatKeyCaseSensitive
                .setBusinessObjectFormatFileType(businessObjectFormatEntity.getFileType().getCode());
    }

    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntityJoin = businessObjectFormatEntityJoin
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntityJoin = businessObjectFormatEntityJoin
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntityJoin = businessObjectDefinitionEntityJoin
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntityJoin = businessObjectDataEntityRoot
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntityJoin = storageUnitEntityJoin
            .join(StorageUnitEntity_.status);
    Join<StorageUnitEntity, StorageEntity> storageEntityJoin = storageUnitEntityJoin
            .join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntityJoin = storageEntityJoin
            .join(StorageEntity_.storagePlatform);

    // Create the path.
    Expression<String> partitionValue;
    SingularAttribute<BusinessObjectDataEntity, String> singleValuedAttribute = BUSINESS_OBJECT_DATA_PARTITIONS
            .get(partitionColumnPosition - 1);
    switch (aggregateFunction) {
    case GREATEST:
        partitionValue = builder.greatest(businessObjectDataEntityRoot.get(singleValuedAttribute));
        break;
    case LEAST:
        partitionValue = builder.least(businessObjectDataEntityRoot.get(singleValuedAttribute));
        break;
    default:
        throw new IllegalArgumentException("Invalid aggregate function found: \"" + aggregateFunction + "\".");
    }

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate mainQueryRestriction = builder.equal(namespaceEntityJoin.get(NamespaceEntity_.code),
            businessObjectFormatKeyCaseSensitive.getNamespace());
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(businessObjectDefinitionEntityJoin.get(BusinessObjectDefinitionEntity_.name),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectDefinitionName()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectFormatUsage().toUpperCase()));
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.equal(fileTypeEntityJoin.get(FileTypeEntity_.code),
                    businessObjectFormatKeyCaseSensitive.getBusinessObjectFormatFileType()));

    // If a business object format version was specified, use it.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.equal(
                        businessObjectFormatEntityJoin
                                .get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
                        businessObjectFormatKey.getBusinessObjectFormatVersion()));
    }

    // If a data version was specified, use it.
    if (businessObjectDataVersion != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction,
                builder.equal(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.version),
                        businessObjectDataVersion));
    }
    // Business object data version is not specified, so get the latest one as per specified business object data status in the specified storage.
    else {
        Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria,
                businessObjectDataEntityRoot, businessObjectFormatEntityJoin, businessObjectDataStatus,
                storageNames, storagePlatformType, excludedStoragePlatformType, false);

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

    // Add an inclusive upper bound partition value restriction if specified.
    if (upperBoundPartitionValue != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.lessThanOrEqualTo(
                businessObjectDataEntityRoot.get(singleValuedAttribute), upperBoundPartitionValue));
    }

    // Add an inclusive lower bound partition value restriction if specified.
    if (lowerBoundPartitionValue != null) {
        mainQueryRestriction = builder.and(mainQueryRestriction, builder.greaterThanOrEqualTo(
                businessObjectDataEntityRoot.get(singleValuedAttribute), lowerBoundPartitionValue));
    }

    // If specified, add restriction on storage.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            getQueryRestrictionOnStorage(builder, storageEntityJoin, storagePlatformEntityJoin, storageNames,
                    storagePlatformType, excludedStoragePlatformType));

    // Search across only "available" storage units.
    mainQueryRestriction = builder.and(mainQueryRestriction,
            builder.isTrue(storageUnitStatusEntityJoin.get(StorageUnitStatusEntity_.available)));

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

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