Example usage for javax.persistence.criteria CriteriaBuilder greaterThanOrEqualTo

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

Introduction

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

Prototype

<Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> x, Y y);

Source Link

Document

Create a predicate for testing whether the first argument is greater than or equal to the second.

Usage

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/* ww  w  .  j  av  a2s .  c  om*/
 *
 * @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.jasig.portal.events.aggr.JpaBaseAggregationDao.java

@Override
public final void afterPropertiesSet() throws Exception {
    this.timeDimensionParameter = this.createParameterExpression(TimeDimension.class, "timeDimension");
    this.dateDimensionParameter = this.createParameterExpression(DateDimension.class, "dateDimension");
    this.intervalParameter = this.createParameterExpression(AggregationInterval.class, "interval");
    this.aggregatedGroupParameter = this.createParameterExpression(AggregatedGroupMapping.class,
            "aggregatedGroup");
    this.aggregatedGroupsParameter = this.createParameterExpression(Set.class, "aggregatedGroups");
    this.startDate = this.createParameterExpression(LocalDate.class, "startDate");
    this.endMinusOneDate = this.createParameterExpression(LocalDate.class, "endMinusOneDate");
    this.endDate = this.createParameterExpression(LocalDate.class, "endDate");
    this.startTime = this.createParameterExpression(LocalTime.class, "startTime");
    this.endTime = this.createParameterExpression(LocalTime.class, "endTime");
    this.createParameterExpressions();

    this.findAggregationByDateTimeIntervalQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override//  w  ww .j ava2s  .  c  om
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);

                    addFetches(ba);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(
                            cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter),
                            cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter),
                            cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));

                    return criteriaQuery;
                }
            });

    this.findAggregationByDateTimeIntervalGroupQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);
                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates
                            .add(cb.equal(ba.get(BaseAggregationImpl_.dateDimension), dateDimensionParameter));
                    keyPredicates
                            .add(cb.equal(ba.get(BaseAggregationImpl_.timeDimension), timeDimensionParameter));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    keyPredicates.add(
                            cb.equal(ba.get(BaseAggregationImpl_.aggregatedGroup), aggregatedGroupParameter));
                    addAggregationSpecificKeyPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));

                    return criteriaQuery;
                }
            });

    this.findAggregationsByDateRangeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);
                    final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension,
                            JoinType.LEFT);
                    final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension,
                            JoinType.LEFT);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates.add(cb.and( //Restrict results by outer date range
                            cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate),
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endDate)));
                    keyPredicates.add(cb.or( //Restrict start of range by time as well
                            cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate),
                            cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime)));
                    keyPredicates.add(cb.or( //Restrict end of range by time as well
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate),
                            cb.lessThan(td.get(TimeDimensionImpl_.time), endTime)));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    keyPredicates
                            .add(ba.get(BaseAggregationImpl_.aggregatedGroup).in(aggregatedGroupsParameter));
                    addAggregationSpecificKeyPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));
                    criteriaQuery.orderBy(cb.desc(dd.get(DateDimensionImpl_.date)),
                            cb.desc(td.get(TimeDimensionImpl_.time)));

                    return criteriaQuery;
                }
            });

    /*
     * Similar to the previous query but only returns aggregates that also match the unclosed predicate generated
     * by the subclass. This is used for finding aggregates that missed having intervalComplete called due to
     * interval boundary placement.
     */
    this.findUnclosedAggregationsByDateRangeQuery = this
            .createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<T>>() {
                @Override
                public CriteriaQuery<T> apply(CriteriaBuilder cb) {
                    final CriteriaQuery<T> criteriaQuery = cb.createQuery(aggregationEntityType);

                    final Root<T> ba = criteriaQuery.from(aggregationEntityType);
                    final Join<T, DateDimensionImpl> dd = ba.join(BaseAggregationImpl_.dateDimension,
                            JoinType.LEFT);
                    final Join<T, TimeDimensionImpl> td = ba.join(BaseAggregationImpl_.timeDimension,
                            JoinType.LEFT);

                    addFetches(ba);

                    final List<Predicate> keyPredicates = new ArrayList<Predicate>();
                    keyPredicates.add(cb.and( //Restrict results by outer date range
                            cb.greaterThanOrEqualTo(dd.get(DateDimensionImpl_.date), startDate),
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endDate)));
                    keyPredicates.add(cb.or( //Restrict start of range by time as well
                            cb.greaterThan(dd.get(DateDimensionImpl_.date), startDate),
                            cb.greaterThanOrEqualTo(td.get(TimeDimensionImpl_.time), startTime)));
                    keyPredicates.add(cb.or( //Restrict end of range by time as well
                            cb.lessThan(dd.get(DateDimensionImpl_.date), endMinusOneDate),
                            cb.lessThan(td.get(TimeDimensionImpl_.time), endTime)));
                    keyPredicates.add(cb.equal(ba.get(BaseAggregationImpl_.interval), intervalParameter));
                    //No aggregation specific key bits here, we only have start/end/interval parameters to work with
                    addUnclosedPredicate(cb, ba, keyPredicates);

                    criteriaQuery.select(ba);
                    criteriaQuery.where(keyPredicates.toArray(new Predicate[keyPredicates.size()]));

                    return criteriaQuery;
                }
            });

    this.createCriteriaQueries();
}

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 w  w  w .  j ava  2s  .c  o m*/
        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.xiaoqiaotq.util.persistence.DynamicSpecifications.java

public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters,
        final Class<T> entityClazz) {
    return new Specification<T>() {
        @Override// w w  w.  ja va2s  .co  m
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if ((filters != null) && !(filters.isEmpty())) {

                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:
                        predicates.add(builder.equal(expression, filter.value));
                        break;
                    case NEQ:
                        predicates.add(builder.notEqual(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;
                    }
                }

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

            return builder.conjunction();
        }
    };
}