Example usage for javax.persistence.criteria CriteriaBuilder and

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

Introduction

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

Prototype

Predicate and(Expression<Boolean> x, Expression<Boolean> y);

Source Link

Document

Create a conjunction of the given boolean expressions.

Usage

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

/**
 * Creates a predicate for partition value filters.
 *
 * @param businessDataSearchKey businessDataSearchKey
 * @param businessObjectDataEntity businessObjectDataEntity
 * @param businessObjectFormatEntity businessObjectFormatEntity
 * @param builder builder//from w  w  w .  j a v a2s .  c o m
 * @param predicatePram predicate parameter
 *
 * @return the predicate
 */
private Predicate createPartitionValueFilters(BusinessObjectDataSearchKey businessDataSearchKey,
        Root<BusinessObjectDataEntity> businessObjectDataEntity,
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity,
        CriteriaBuilder builder, Predicate predicatePram) {
    Predicate predicate = predicatePram;

    if (businessDataSearchKey.getPartitionValueFilters() != null
            && !businessDataSearchKey.getPartitionValueFilters().isEmpty()) {
        for (PartitionValueFilter partitionFilter : businessDataSearchKey.getPartitionValueFilters()) {
            Join<BusinessObjectFormatEntity, SchemaColumnEntity> schemaEntity = businessObjectFormatEntity
                    .join(BusinessObjectFormatEntity_.schemaColumns);

            List<String> partitionValues = partitionFilter.getPartitionValues();

            predicate = builder.and(predicate,
                    builder.equal(builder.upper(schemaEntity.get(SchemaColumnEntity_.name)),
                            partitionFilter.getPartitionKey().toUpperCase()));
            predicate = builder.and(predicate,
                    builder.isNotNull(schemaEntity.get(SchemaColumnEntity_.partitionLevel)));

            if (partitionValues != null && !partitionValues.isEmpty()) {
                predicate = builder.and(predicate, builder.or(
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 1),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 2),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 3),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 4),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4)
                                        .in(partitionValues)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 5),
                                businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5)
                                        .in(partitionValues))));
            } else if (partitionFilter.getPartitionValueRange() != null) {
                PartitionValueRange partitionRange = partitionFilter.getPartitionValueRange();
                String startPartitionValue = partitionRange.getStartPartitionValue();
                String endPartitionValue = partitionRange.getEndPartitionValue();

                predicate = builder.and(predicate, builder.or(
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 1),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 2),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 3),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 4),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4),
                                        endPartitionValue)),
                        builder.and(builder.equal(schemaEntity.get(SchemaColumnEntity_.partitionLevel), 5),
                                builder.greaterThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5),
                                        startPartitionValue),
                                builder.lessThanOrEqualTo(
                                        businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5),
                                        endPartitionValue))));
            }
        }
    }

    return predicate;
}

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

/**
 * Apply retention expiration filter to the main query predicate.
 *
 * @param businessObjectDataSearchKey the business object data search key
 * @param businessObjectDataEntityRoot the criteria root which is a business object data entity
 * @param businessObjectFormatEntityJoin the join with the business object format table
 * @param builder the criteria builder//from  w w  w. j  a  va 2  s.  c  o m
 * @param mainQueryPredicate the main query predicate to be updated
 *
 * @return the updated main query predicate
 */
private Predicate applyRetentionExpirationFilter(BusinessObjectDataSearchKey businessObjectDataSearchKey,
        Root<BusinessObjectDataEntity> businessObjectDataEntityRoot,
        Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin,
        CriteriaBuilder builder, Predicate mainQueryPredicate) {
    // Create a business object definition key per specified search key.
    BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey(
            businessObjectDataSearchKey.getNamespace(),
            businessObjectDataSearchKey.getBusinessObjectDefinitionName());

    // Get latest versions of all business object formats that registered with the business object definition.
    List<BusinessObjectFormatEntity> businessObjectFormatEntities = businessObjectFormatDao
            .getLatestVersionBusinessObjectFormatsByBusinessObjectDefinition(businessObjectDefinitionKey);

    // Create a result predicate to join all retention expiration predicates created per selected business object formats.
    Predicate businessObjectDefinitionRetentionExpirationPredicate = null;

    // Get the current database timestamp to be used to select expired business object data per BDATA_RETENTION_DATE retention type.
    Timestamp currentTimestamp = getCurrentTimestamp();

    // Create a predicate for each business object format with the retention information.
    for (BusinessObjectFormatEntity businessObjectFormatEntity : businessObjectFormatEntities) {
        if (businessObjectFormatEntity.getRetentionType() != null) {
            // Create a retention expiration predicate for this business object format.
            Predicate businessObjectFormatRetentionExpirationPredicate = null;

            if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(),
                    RetentionTypeEntity.BDATA_RETENTION_DATE)) {
                // Select business object data that has expired per its explicitly configured retention expiration date.
                businessObjectFormatRetentionExpirationPredicate = builder.lessThan(
                        businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.retentionExpiration),
                        currentTimestamp);
            } else if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(),
                    RetentionTypeEntity.PARTITION_VALUE)
                    && businessObjectFormatEntity.getRetentionPeriodInDays() != null) {
                // Compute the retention expiration date and convert it to the date format to match against partition values.
                String retentionExpirationDate = DateFormatUtils.format(
                        DateUtils.addDays(new Date(),
                                -1 * businessObjectFormatEntity.getRetentionPeriodInDays()),
                        DEFAULT_SINGLE_DAY_DATE_MASK);

                // Create a predicate to compare business object data primary partition value against the retention expiration date.
                businessObjectFormatRetentionExpirationPredicate = builder.lessThan(
                        businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.partitionValue),
                        retentionExpirationDate);
            }

            // If it was initialize, complete processing of retention expiration predicate for this business object format.
            if (businessObjectFormatRetentionExpirationPredicate != null) {
                // Update the predicate to match this business object format w/o version.
                businessObjectFormatRetentionExpirationPredicate = builder.and(
                        businessObjectFormatRetentionExpirationPredicate,
                        builder.equal(
                                builder.upper(
                                        businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                                businessObjectFormatEntity.getUsage().toUpperCase()));
                businessObjectFormatRetentionExpirationPredicate = builder.and(
                        businessObjectFormatRetentionExpirationPredicate,
                        builder.equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileType),
                                businessObjectFormatEntity.getFileType()));

                // Add this business object format specific retention expiration predicate to other
                // retention expiration predicates created for the specified business object definition.
                if (businessObjectDefinitionRetentionExpirationPredicate == null) {
                    businessObjectDefinitionRetentionExpirationPredicate = businessObjectFormatRetentionExpirationPredicate;
                } else {
                    businessObjectDefinitionRetentionExpirationPredicate = builder.or(
                            businessObjectDefinitionRetentionExpirationPredicate,
                            businessObjectFormatRetentionExpirationPredicate);
                }
            }
        }
    }

    // Fail if no retention expiration predicates got created per specified business objject definition.
    Assert.notNull(businessObjectDefinitionRetentionExpirationPredicate, String.format(
            "Business object definition with name \"%s\" and namespace \"%s\" has no business object formats with supported retention type.",
            businessObjectDefinitionKey.getBusinessObjectDefinitionName(),
            businessObjectDefinitionKey.getNamespace()));

    // Add created business object definition retention expiration predicate to the main query predicate passed to this method and return the result.
    return builder.and(mainQueryPredicate, businessObjectDefinitionRetentionExpirationPredicate);
}

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

/**
 * Apply attribute value filters to the main query predicate.
 *
 * @param businessDataSearchKey the business object data search key
 * @param businessObjectDataEntityRoot the criteria root which is a business object data entity
 * @param builder the criteria builder/*from  w  ww .j a va2 s  . c om*/
 * @param mainQueryPredicate the main query predicate to be updated
 *
 * @return the updated main query predicate
 */
private Predicate applyAttributeValueFilters(final BusinessObjectDataSearchKey businessDataSearchKey,
        final Root<BusinessObjectDataEntity> businessObjectDataEntityRoot, final CriteriaBuilder builder,
        Predicate mainQueryPredicate) {
    if (!CollectionUtils.isEmpty(businessDataSearchKey.getAttributeValueFilters())) {
        for (AttributeValueFilter attributeValueFilter : businessDataSearchKey.getAttributeValueFilters()) {
            Join<BusinessObjectDataEntity, BusinessObjectDataAttributeEntity> dataAttributeEntity = businessObjectDataEntityRoot
                    .join(BusinessObjectDataEntity_.attributes);

            if (!StringUtils.isEmpty(attributeValueFilter.getAttributeName())) {
                mainQueryPredicate = builder.and(mainQueryPredicate,
                        builder.equal(dataAttributeEntity.get(BusinessObjectDataAttributeEntity_.name),
                                attributeValueFilter.getAttributeName()));
            }

            if (!StringUtils.isEmpty(attributeValueFilter.getAttributeValue())) {
                mainQueryPredicate = builder.and(mainQueryPredicate,
                        builder.equal(dataAttributeEntity.get(BusinessObjectDataAttributeEntity_.value),
                                attributeValueFilter.getAttributeValue()));
            }
        }
    }

    return mainQueryPredicate;
}

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

/**
 * Apply a predicate for registration date range filter.
 *
 * @param registrationDateRangeFilter the registration date range filter, not null
 * @param businessObjectDataEntity the business object data entity
 * @param builder the query builder/*from   w w w  .j  a  va  2s . c  o  m*/
 * @param predicate the predicate to be updated
 *
 * @return the predicate with added registration date range filter
 */
private Predicate applyRegistrationDateRangeFilter(RegistrationDateRangeFilter registrationDateRangeFilter,
        Root<BusinessObjectDataEntity> businessObjectDataEntity, CriteriaBuilder builder, Predicate predicate) {
    // Apply predicate for registration start date and removed the time portion of the date.
    if (registrationDateRangeFilter.getStartRegistrationDate() != null) {
        predicate = builder.and(predicate, builder.greaterThanOrEqualTo(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn),
                HerdDateUtils.resetTimeToMidnight(registrationDateRangeFilter.getStartRegistrationDate())));
    }

    // Apply predicate for registration end date. Removed time portion of the date and added one day to get the result till the end of the day
    if (registrationDateRangeFilter.getEndRegistrationDate() != null) {
        predicate = builder.and(predicate, builder.lessThan(
                businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn),
                HerdDateUtils.addDays(
                        HerdDateUtils.resetTimeToMidnight(registrationDateRangeFilter.getEndRegistrationDate()),
                        1)));
    }

    return predicate;
}

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 ww  . jav  a  2s  .  c  om
 * @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.BusinessObjectDataNotificationRegistrationDaoImpl.java

@Override
public BusinessObjectDataNotificationRegistrationEntity getBusinessObjectDataNotificationRegistrationByAltKey(
        NotificationRegistrationKey key) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataNotificationRegistrationEntity> criteria = builder
            .createQuery(BusinessObjectDataNotificationRegistrationEntity.class);

    // The criteria root is the business object data notification registration entity.
    Root<BusinessObjectDataNotificationRegistrationEntity> businessObjectDataNotificationEntity = criteria
            .from(BusinessObjectDataNotificationRegistrationEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataNotificationRegistrationEntity, NamespaceEntity> namespaceEntity = businessObjectDataNotificationEntity
            .join(BusinessObjectDataNotificationRegistrationEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            key.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(//  w  ww .j  a  v a2s . c om
                    builder.upper(businessObjectDataNotificationEntity
                            .get(BusinessObjectDataNotificationRegistrationEntity_.name)),
                    key.getNotificationName().toUpperCase()));

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

    return executeSingleResultQuery(criteria, String.format(
            "Found more than one business object data notification registration with with parameters {namespace=\"%s\", notificationName=\"%s\"}.",
            key.getNamespace(), key.getNotificationName()));
}

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

@Override
public BusinessObjectDefinitionEntity getBusinessObjectDefinitionByKey(
        BusinessObjectDefinitionKey businessObjectDefinitionKey) {
    // 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);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(/*  w  ww  . j  a v a  2s. c o  m*/
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

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

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

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

@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)));
    }//from ww  w .j a v  a 2s  . c  o  m

    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.BusinessObjectFormatDaoImpl.java

@Override
public List<BusinessObjectFormatKey> getBusinessObjectFormatsWithFilters(
        BusinessObjectDefinitionKey businessObjectDefinitionKey, String businessObjectFormatUsage,
        boolean latestBusinessObjectFormatVersion) {
    // 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 format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Expression<Integer> maxBusinessObjectFormatVersionExpression = builder
            .max(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(/*from   w ww  .  j  a va  2s  .  c  o m*/
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the business object format usage where parameter is not empty
    if (StringUtils.isNotEmpty(businessObjectFormatUsage)) {
        queryRestriction = builder.and(queryRestriction,
                builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
                        businessObjectFormatUsage.toUpperCase()));
    }

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeCodeColumn,
            latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                    : businessObjectFormatVersionColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // If only the latest (maximum) business object format versions to be returned, create and apply the group by clause.
    if (latestBusinessObjectFormatVersion) {
        List<Expression<?>> grouping = new ArrayList<>();
        grouping.add(namespaceCodeColumn);
        grouping.add(businessObjectDefinitionNameColumn);
        grouping.add(businessObjectFormatUsageColumn);
        grouping.add(fileTypeCodeColumn);
        criteria.groupBy(grouping);
    }

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatUsageColumn));
    orderBy.add(builder.asc(fileTypeCodeColumn));
    if (!latestBusinessObjectFormatVersion) {
        orderBy.add(builder.asc(businessObjectFormatVersionColumn));
    }
    criteria.orderBy(orderBy);

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

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectFormatKey> businessObjectFormatKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectFormatKey businessObjectFormatKey = new BusinessObjectFormatKey();
        businessObjectFormatKeys.add(businessObjectFormatKey);
        businessObjectFormatKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectFormatKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        businessObjectFormatKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        businessObjectFormatKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        businessObjectFormatKey.setBusinessObjectFormatVersion(
                tuple.get(latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                        : businessObjectFormatVersionColumn));
    }

    return businessObjectFormatKeys;
}

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

@Override
public List<BusinessObjectFormatEntity> getLatestVersionBusinessObjectFormatsByBusinessObjectDefinition(
        BusinessObjectDefinitionKey businessObjectDefinitionKey) {
    // 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, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(//  ww  w.  j  a va2s  .  co m
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)));
    orderBy.add(builder.asc(fileTypeEntity.get(FileTypeEntity_.code)));

    queryRestriction = builder.and(queryRestriction,
            builder.equal(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.latestVersion), true));

    criteria.orderBy(orderBy);
    // Add the where clause.
    criteria.where(queryRestriction);
    return entityManager.createQuery(criteria).getResultList();
}