Example usage for javax.persistence.criteria CriteriaBuilder not

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

Introduction

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

Prototype

Predicate not(Expression<Boolean> restriction);

Source Link

Document

Create a negation of the given restriction.

Usage

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

/**
 * {@inheritDoc}/*from   w ww. j a v  a2 s .  c  o m*/
 */
@Override
public List<BusinessObjectDataEntity> getBusinessObjectDataFromStorageOlderThan(String storageName,
        int thresholdMinutes, List<String> businessObjectDataStatusesToIgnore) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.class);

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.status);

    // Compute threshold timestamp based on the current database timestamp and threshold minutes.
    Timestamp thresholdTimestamp = subtractMinutes(getCurrentTimestamp(), thresholdMinutes);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageName.toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.not(businessObjectDataStatusEntity
            .get(BusinessObjectDataStatusEntity_.code).in(businessObjectDataStatusesToIgnore)));
    queryRestriction = builder.and(queryRestriction, builder.lessThanOrEqualTo(
            businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn), thresholdTimestamp));

    // Order the results by file path.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn));

    // Add the clauses for the query.
    criteria.select(businessObjectDataEntity).where(queryRestriction).orderBy(orderByCreatedOn);

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

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

/**
 * {@inheritDoc}/*from   w w  w  .  ja  v  a 2 s  .  co m*/
 */
@Override
public List<BusinessObjectDataEntity> getBusinessObjectDataFromStorageOlderThan(String storageName,
        int thresholdMinutes, List<String> businessObjectDataStatusesToIgnore) {
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDataEntity> criteria = builder.createQuery(BusinessObjectDataEntity.class);

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.status);

    // Compute threshold timestamp based on the current database timestamp and threshold minutes.
    Timestamp thresholdTimestamp = HerdDateUtils.addMinutes(getCurrentTimestamp(), -thresholdMinutes);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)),
            storageName.toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.not(businessObjectDataStatusEntity
            .get(BusinessObjectDataStatusEntity_.code).in(businessObjectDataStatusesToIgnore)));
    queryRestriction = builder.and(queryRestriction, builder.lessThanOrEqualTo(
            businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn), thresholdTimestamp));

    // Order the results by file path.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntity.get(BusinessObjectDataEntity_.createdOn));

    // Add the clauses for the query.
    criteria.select(businessObjectDataEntity).where(queryRestriction).orderBy(orderByCreatedOn);

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

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

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

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

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.storageUnits);
    Join<BusinessObjectDataEntity, BusinessObjectDataStatusEntity> businessObjectDataStatusEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.status);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity
            .join(BusinessObjectDataEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return result;
}

From source file:org.jboss.pnc.datastore.predicates.rsql.RSQLNodeTravellerPredicate.java

public RSQLNodeTravellerPredicate(Class<Entity> entityClass, String rsql) throws RSQLParserException {
    operations.put(RSQLOperators.EQUAL, new AbstractTransformer<Entity>() {
        @Override//from   ww  w .j  av  a 2s  .c  om
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.equal(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.NOT_EQUAL, new AbstractTransformer<Entity>() {
        @Override
        Predicate transform(Root<Entity> r, Path<?> selectedPath, CriteriaBuilder cb, String operand,
                List<Object> convertedArguments) {
            return cb.notEqual(selectedPath, convertedArguments.get(0));
        }
    });

    operations.put(RSQLOperators.GREATER_THAN, (r, cb, clazz, operand, arguments) -> cb
            .greaterThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.GREATER_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .greaterThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN, (r, cb, clazz, operand, arguments) -> cb
            .lessThan((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.LESS_THAN_OR_EQUAL, (r, cb, clazz, operand, arguments) -> cb
            .lessThanOrEqualTo((Path) selectWithOperand(r, operand, clazz), arguments.get(0)));
    operations.put(RSQLOperators.IN,
            (r, cb, clazz, operand, arguments) -> ((Path) selectWithOperand(r, operand, clazz)).in(arguments));
    operations.put(RSQLOperators.NOT_IN, (r, cb, clazz, operand, arguments) -> cb
            .not(((Path) selectWithOperand(r, operand, clazz)).in(arguments)));
    operations.put(LIKE,
            (r, cb, clazz, operand, arguments) -> cb.like(cb.lower((Path) selectWithOperand(r, operand, clazz)),
                    preprocessLikeOperatorArgument(arguments.get(0).toLowerCase())));
    operations.put(IS_NULL, (r, cb, clazz, operand, arguments) -> {
        if (Boolean.parseBoolean(arguments.get(0))) {
            return cb.isNull((Path) selectWithOperand(r, operand, clazz));
        } else {
            return cb.isNotNull((Path) selectWithOperand(r, operand, clazz));
        }
    });

    Set<ComparisonOperator> operators = RSQLOperators.defaultOperators();
    operators.add(LIKE);
    operators.add(IS_NULL);

    rootNode = new RSQLParser(operators).parse(preprocessRSQL(rsql));
    selectingClass = entityClass;
}

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

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

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

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

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

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

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

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

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

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

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

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