Example usage for javax.persistence Tuple get

List of usage examples for javax.persistence Tuple get

Introduction

In this page you can find the example usage for javax.persistence Tuple get.

Prototype

Object get(int i);

Source Link

Document

Get the value of the element at the specified position in the result tuple.

Usage

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

/**
 * TODO: Make this method the main body of getStorageUploadStatsByBusinessObjectDefinition once we migrate away from Oracle TODO:
 * getStorageUploadStatsByBusinessObjectDefinition that uses storage file view. This method is meant to be database agnostic.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range/*from  ww w. j  a  v a2 s  .co m*/
 *
 * @return the upload statistics
 */
private StorageBusinessObjectDefinitionDailyUploadStats getStorageUploadStatsByBusinessObjectDefinitionDatabaseAgnostic(
        StorageAlternateKeyDto storageAlternateKey, DateRangeDto dateRange) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    Root<StorageFileViewEntity> storageFileViewEntity = criteria.from(StorageFileViewEntity.class);

    Path<String> namespaceCode = storageFileViewEntity.get(StorageFileViewEntity_.namespaceCode);
    Path<String> dataProviderCode = storageFileViewEntity.get(StorageFileViewEntity_.dataProviderCode);
    Path<String> businessObjectDefinitionName = storageFileViewEntity
            .get(StorageFileViewEntity_.businessObjectDefinitionName);
    Path<Date> createdDate = storageFileViewEntity.get(StorageFileViewEntity_.createdDate);
    Expression<Long> totalFilesExpression = builder
            .count(storageFileViewEntity.get(StorageFileViewEntity_.storageFileId));
    Expression<Long> totalBytesExpression = builder
            .sum(storageFileViewEntity.get(StorageFileViewEntity_.fileSizeInBytes));

    Predicate storageNameRestriction = builder.equal(
            builder.upper(storageFileViewEntity.get(StorageFileViewEntity_.storageCode)),
            storageAlternateKey.getStorageName().toUpperCase());
    Predicate createDateRestriction = builder.and(
            builder.greaterThanOrEqualTo(createdDate, dateRange.getLowerDate()),
            builder.lessThanOrEqualTo(createdDate, dateRange.getUpperDate()));

    criteria.multiselect(createdDate, namespaceCode, dataProviderCode, businessObjectDefinitionName,
            totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

    // Create the group by clause.
    List<Expression<?>> grouping = new ArrayList<>();
    grouping.add(createdDate);
    grouping.add(namespaceCode);
    grouping.add(dataProviderCode);
    grouping.add(businessObjectDefinitionName);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(createdDate), builder.asc(namespaceCode), builder.asc(dataProviderCode),
            builder.asc(businessObjectDefinitionName));

    // Retrieve and return the storage upload statistics.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();
    StorageBusinessObjectDefinitionDailyUploadStats uploadStats = new StorageBusinessObjectDefinitionDailyUploadStats();

    for (Tuple tuple : tuples) {
        StorageBusinessObjectDefinitionDailyUploadStat uploadStat = new StorageBusinessObjectDefinitionDailyUploadStat();
        uploadStats.getStorageBusinessObjectDefinitionDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(HerdDateUtils.getXMLGregorianCalendarValue(tuple.get(createdDate)));
        uploadStat.setNamespace(tuple.get(namespaceCode));
        uploadStat.setDataProviderName(tuple.get(dataProviderCode));
        uploadStat.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionName));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

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

/**
 * TODO: Remove this method once we migrate away from Oracle getStorageUploadStatsByBusinessObjectDefinition that uses Oracle specific 'trunc' function.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range/*from  w  w  w.ja v a  2  s. com*/
 *
 * @return the upload statistics
 */
private StorageBusinessObjectDefinitionDailyUploadStats getStorageUploadStatsByBusinessObjectDefinitionOracle(
        StorageAlternateKeyDto storageAlternateKey, DateRangeDto dateRange) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage file.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity
            .join(StorageFileEntity_.storageUnit);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity
            .join(StorageUnitEntity_.businessObjectData);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, DataProviderEntity> dataProviderEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.dataProvider);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Create paths and expressions.
    Path<String> namespacePath = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> dataProviderNamePath = dataProviderEntity.get(DataProviderEntity_.name);
    Path<String> businessObjectDefinitionNamePath = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Expression<Date> truncCreatedOnDateExpression = builder.function("trunc", Date.class,
            storageFileEntity.get(StorageFileEntity_.createdOn));
    Expression<Long> totalFilesExpression = builder.count(storageFileEntity.get(StorageFileEntity_.id));
    Expression<Long> totalBytesExpression = builder
            .sum(storageFileEntity.get(StorageFileEntity_.fileSizeBytes));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageAlternateKey.getStorageName().toUpperCase());
    Predicate createDateRestriction = builder.and(
            builder.greaterThanOrEqualTo(truncCreatedOnDateExpression, dateRange.getLowerDate()),
            builder.lessThanOrEqualTo(truncCreatedOnDateExpression, dateRange.getUpperDate()));

    criteria.multiselect(truncCreatedOnDateExpression, namespacePath, dataProviderNamePath,
            businessObjectDefinitionNamePath, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

    // Create the group by clause.
    List<Expression<?>> grouping = new ArrayList<>();

    grouping.add(truncCreatedOnDateExpression);
    grouping.add(namespacePath);
    grouping.add(dataProviderNamePath);
    grouping.add(businessObjectDefinitionNamePath);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(truncCreatedOnDateExpression), builder.asc(namespacePath),
            builder.asc(dataProviderNamePath), builder.asc(businessObjectDefinitionNamePath));

    // Retrieve and return the storage upload statistics.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();
    StorageBusinessObjectDefinitionDailyUploadStats uploadStats = new StorageBusinessObjectDefinitionDailyUploadStats();

    for (Tuple tuple : tuples) {
        StorageBusinessObjectDefinitionDailyUploadStat uploadStat = new StorageBusinessObjectDefinitionDailyUploadStat();
        uploadStats.getStorageBusinessObjectDefinitionDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(
                HerdDateUtils.getXMLGregorianCalendarValue(tuple.get(truncCreatedOnDateExpression)));
        uploadStat.setNamespace(tuple.get(namespacePath));
        uploadStat.setDataProviderName(tuple.get(dataProviderNamePath));
        uploadStat.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNamePath));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

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

@Override
public MultiValuedMap<Integer, String> getStorageFilePathsByStorageUnitIds(List<Integer> storageUnitIds) {
    // Create a map that can hold a collection of values against each key.
    MultiValuedMap<Integer, String> result = new ArrayListValuedHashMap<>();

    // Retrieve the pagination size for the storage file paths query configured in the system.
    Integer paginationSize = configurationHelper
            .getProperty(ConfigurationValue.STORAGE_FILE_PATHS_QUERY_PAGINATION_SIZE, Integer.class);

    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage file.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Get the columns.
    Path<Integer> storageUnitIdColumn = storageFileEntity.get(StorageFileEntity_.storageUnitId);
    Path<String> storageFilePathColumn = storageFileEntity.get(StorageFileEntity_.path);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = getPredicateForInClause(builder, storageUnitIdColumn, storageUnitIds);

    // Add the select clause.
    criteria.multiselect(storageUnitIdColumn, storageFilePathColumn);

    // Add the where clause.
    criteria.where(queryRestriction);/* w w  w .j  a  va  2  s  . c  o  m*/

    // Execute the query using pagination and populate the result map.
    int startPosition = 0;
    while (true) {
        // Run the query to get a list of tuples back.
        List<Tuple> tuples = entityManager.createQuery(criteria).setFirstResult(startPosition)
                .setMaxResults(paginationSize).getResultList();

        // Populate the result map from the returned tuples (i.e. 1 tuple for each row).
        for (Tuple tuple : tuples) {
            // Extract the tuple values.
            Integer storageUnitId = tuple.get(storageUnitIdColumn);
            String storageFilePath = tuple.get(storageFilePathColumn);

            // Update the result map.
            result.put(storageUnitId, storageFilePath);
        }

        // Break out of the while loop if we got less results than the pagination size.
        if (tuples.size() < paginationSize) {
            break;
        }

        // Increment the start position.
        startPosition += paginationSize;
    }

    return result;
}

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

/**
 * Retrieves a list of storage unit availability DTOs per specified parameters. This method processes a sublist of partition filters specified by
 * partitionFilterSubListFromIndex and partitionFilterSubListSize parameters.
 *
 * @param businessObjectFormatKey the business object format key (case-insensitive). If a business object format version isn't specified, the latest
 * available format version for each partition value will be used
 * @param partitionFilters the list of partition filter to be used to select business object data instances. Each partition filter contains a list of
 * primary and sub-partition values in the right order up to the maximum partition levels allowed by business object data registration - with partition
 * values for the relative partitions not to be used for selection passed as nulls
 * @param businessObjectDataVersion the business object data version. If a business object data version isn't specified, the latest data version based on
 * the specified business object data status is returned
 * @param businessObjectDataStatus the business object data status. This parameter is ignored when the business object data version is specified. When
 * business object data version and business object data status both are not specified, the latest data version for each set of partition values will be
 * used regardless of the status//from  w w  w  .  j a  v a2  s  .c  om
 * @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 storage names is not empty
 * @param excludedStoragePlatformType the optional storage platform type to be excluded from search. It is ignored when the list of storage names is not
 * empty or the storage platform type is specified
 * @param partitionFilterSubListFromIndex the index of the first element in the partition filter sublist
 * @param partitionFilterSubListSize the size of the partition filter sublist
 * @param selectOnlyAvailableStorageUnits specifies if only available storage units will be selected or any storage units regardless of their status
 *
 * @return the list of storage unit availability DTOs sorted by partition values
 */
private List<StorageUnitAvailabilityDto> getStorageUnitsByPartitionFilters(
        BusinessObjectFormatKey businessObjectFormatKey, List<List<String>> partitionFilters,
        Integer businessObjectDataVersion, String businessObjectDataStatus, List<String> storageNames,
        String storagePlatformType, String excludedStoragePlatformType, boolean selectOnlyAvailableStorageUnits,
        int partitionFilterSubListFromIndex, int partitionFilterSubListSize) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage unit.
    Root<StorageUnitEntity> storageUnitEntity = criteria.from(StorageUnitEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitEntity, BusinessObjectDataEntity> businessObjectDataEntity = storageUnitEntity
            .join(StorageUnitEntity_.businessObjectData);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<StorageEntity, StoragePlatformEntity> storagePlatformEntity = storageEntity
            .join(StorageEntity_.storagePlatform);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);
    Join<StorageUnitEntity, StorageUnitStatusEntity> storageUnitStatusEntity = storageUnitEntity
            .join(StorageUnitEntity_.status);

    // 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, namespaceEntity, businessObjectFormatKey, false);

    // If a format version was not specified, use the latest available for this set of partition values.
    if (businessObjectFormatKey.getBusinessObjectFormatVersion() == null) {
        // Get the latest available format version for this set of partition values and per other restrictions.
        Subquery<Integer> subQuery = getMaximumBusinessObjectFormatVersionSubQuery(builder, criteria,
                businessObjectDefinitionEntity, businessObjectFormatEntity, fileTypeEntity,
                businessObjectDataEntity, businessObjectDataVersion, businessObjectDataStatus, storageNames,
                storagePlatformType, excludedStoragePlatformType, selectOnlyAvailableStorageUnits);

        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, storageNames,
                storagePlatformType, excludedStoragePlatformType, selectOnlyAvailableStorageUnits);

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

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

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

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

    // Get the columns.
    Path<Integer> storageUnitIdColumn = storageUnitEntity.get(StorageUnitEntity_.id);
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Path<String> primaryPartitionValueColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue);
    Path<String> subPartitionValue1Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue2);
    Path<String> subPartitionValue2Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue3);
    Path<String> subPartitionValue3Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue4);
    Path<String> subPartitionValue4Column = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.partitionValue5);
    Path<Integer> businessObjectDataVersionColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.version);
    Path<String> storageNameColumn = storageEntity.get(StorageEntity_.name);
    Path<String> storageUnitDirectoryPathColumn = storageUnitEntity.get(StorageUnitEntity_.directoryPath);
    Path<String> businessObjectDataStatusColumn = businessObjectDataEntity
            .get(BusinessObjectDataEntity_.statusCode);
    Path<String> storageUnitStatusColumn = storageUnitEntity.get(StorageUnitEntity_.statusCode);
    Path<Boolean> storageUnitAvailableColumn = storageUnitStatusEntity.get(StorageUnitStatusEntity_.available);

    // Add the clauses for the query.
    criteria.multiselect(storageUnitIdColumn, namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeColumn, businessObjectFormatVersionColumn,
            primaryPartitionValueColumn, subPartitionValue1Column, subPartitionValue2Column,
            subPartitionValue3Column, subPartitionValue4Column, businessObjectDataVersionColumn,
            storageNameColumn, storageUnitDirectoryPathColumn, businessObjectDataStatusColumn,
            storageUnitStatusColumn, storageUnitAvailableColumn).where(mainQueryRestriction).orderBy(orderBy);

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

    // Build a list of storage unit availability DTOs to return.
    List<StorageUnitAvailabilityDto> storageUnitAvailabilityDtos = new ArrayList<>();
    for (Tuple tuple : tuples) {
        storageUnitAvailabilityDtos.add(new StorageUnitAvailabilityDto(tuple.get(storageUnitIdColumn),
                new BusinessObjectDataKey(tuple.get(namespaceCodeColumn),
                        tuple.get(businessObjectDefinitionNameColumn),
                        tuple.get(businessObjectFormatUsageColumn), tuple.get(fileTypeColumn),
                        tuple.get(businessObjectFormatVersionColumn), tuple.get(primaryPartitionValueColumn),
                        getSubPartitionValuesFromRawSubPartitionValues(Arrays.asList(
                                tuple.get(subPartitionValue1Column), tuple.get(subPartitionValue2Column),
                                tuple.get(subPartitionValue3Column), tuple.get(subPartitionValue4Column))),
                        tuple.get(businessObjectDataVersionColumn)),
                tuple.get(storageNameColumn), tuple.get(storageUnitDirectoryPathColumn),
                tuple.get(businessObjectDataStatusColumn), tuple.get(storageUnitStatusColumn),
                tuple.get(storageUnitAvailableColumn)));
    }

    return storageUnitAvailabilityDtos;
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpa2.JpaHelper.java

/**
 *
 * @param <T>/* w w w . ja va 2s.  c  o m*/
 * @param tuple
 * @param object
 * @return
 */
public static <T> T mapTupleToObject(Tuple tuple, T object)
        throws IllegalAccessException, InvocationTargetException {
    assert tuple != null;
    assert object != null;
    try {
        for (TupleElement<?> element : tuple.getElements()) {
            if (element.getAlias() != null) {
                BeanUtils.setProperty(object, element.getAlias(), tuple.get(element.getAlias()));
            }
        }
        return object;
    } catch (Exception e) {
        log.error("mapTupleToObject not successful", e);
        throw new QueryConfigException("mapTupleToObject not successful");
    }
}

From source file:org.xlcloud.service.dao.JpaVirtualClusterDefinitionsDao.java

/** {@inheritDoc} */
@Override/*from   ww w .ja  v  a2s  .co m*/
public List<VirtualClusterDefinitionModel> findByTypeAndTags(Long accountId, String type, Set<String> tags,
        boolean paged) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("finding vc definitions with type id: " + type + " and following tag ids:"
                + ToStringBuilder.reflectionToString(tags));
    }

    CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
    CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
    Root<VirtualClusterDefinitionModel> vcDefRoot = query.from(VirtualClusterDefinitionModel.class);

    Predicate typePredicate = criteriaBuilder.equal(vcDefRoot.get(VirtualClusterDefinitionModel_.type), type);
    Predicate tagsPredicate = vcDefRoot.get(VirtualClusterDefinitionModel_.tags).in(tags);

    boolean skipTagsJoin = tags.isEmpty();
    Predicate predicate = skipTagsJoin ? typePredicate : criteriaBuilder.and(typePredicate, tagsPredicate);

    Predicate scopePredicate;
    if (accountId != null) {
        Predicate accountPredicate = criteriaBuilder
                .equal(vcDefRoot.get(VirtualClusterDefinitionModel_.accountId), accountId);
        Predicate privatePredicate = criteriaBuilder
                .equal(vcDefRoot.get(VirtualClusterDefinitionModel_.catalogScope), CatalogScope.PRIVATE);
        scopePredicate = criteriaBuilder.and(accountPredicate, privatePredicate);
    } else {
        scopePredicate = criteriaBuilder.equal(vcDefRoot.get(VirtualClusterDefinitionModel_.catalogScope),
                CatalogScope.PUBLIC);
    }

    predicate = criteriaBuilder.and(predicate, scopePredicate);

    query.multiselect(vcDefRoot, criteriaBuilder.count(vcDefRoot));
    query.where(predicate);
    query.groupBy(vcDefRoot);
    if (!skipTagsJoin) {
        query.having(criteriaBuilder.equal(criteriaBuilder.count(vcDefRoot), tags.size()));
    }

    List<Tuple> list = getResultList(query, vcDefRoot, paged);
    List<VirtualClusterDefinitionModel> results = new LinkedList<VirtualClusterDefinitionModel>();
    for (Tuple t : list) {
        results.add((VirtualClusterDefinitionModel) t.get(0));
    }
    return results;
}