Example usage for javax.persistence.criteria CriteriaBuilder function

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

Introduction

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

Prototype

<T> Expression<T> function(String name, Class<T> type, Expression<?>... args);

Source Link

Document

Create an expression for the execution of a database function.

Usage

From source file:com.carser.viamais.vo.TransactionFilter.java

private Predicate[] getPredicates(CriteriaBuilder cb, Root<Transaction> transaction) {
    List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.hasLength(pattern)) {
        String[] words = pattern.split(" ");
        for (String word : words) {
            Predicate model = cb.like(transaction.get(Transaction_.car).get(Car_.model).get(Model_.name),
                    "%" + word + "%");
            Predicate customer = cb.like(transaction.get(Transaction_.customer).get(Customer_.name),
                    "%" + word + "%");
            predicates.add((cb.or(model, customer)));
        }/*from ww w .  ja  v a 2  s  .  c  o  m*/
    }
    if (StringUtils.hasLength(rg)) {
        predicates.add(cb.like(transaction.get(Transaction_.customer).get(Customer_.rg), "%" + rg + "%"));
    }
    if (StringUtils.hasLength(cpf)) {
        predicates.add(cb.like(transaction.get(Transaction_.customer).get(Customer_.cpf).as(String.class),
                "%" + cpf + "%"));
    }
    if (StringUtils.hasLength(renavam)) {
        predicates.add(cb.like(transaction.get(Transaction_.car).get(Car_.renavam), "%" + renavam + "%"));
    }
    if (StringUtils.hasLength(plate)) {
        predicates.add(cb.equal(transaction.get(Transaction_.car).get(Car_.licensePlate), plate));
    }
    if (StringUtils.hasLength(chassi)) {
        predicates.add(cb.like(transaction.get(Transaction_.car).get(Car_.chassi), "%" + chassi + "%"));
    }
    Expression<Date> date = cb.function("date", Date.class, transaction.get(Transaction_.transactionDate));
    if (startDate != null) {
        predicates.add(cb.greaterThanOrEqualTo(date, startDate));
    }
    if (finalDate != null) {
        predicates.add(cb.lessThanOrEqualTo(date, finalDate));
    }
    if (StringUtils.hasLength(type)) {
        switch (type) {
        case "sale":
            predicates.add(cb.equal(transaction.get(Transaction_.type), Sale.class.getSimpleName()));
            break;
        case "purchase":
            predicates.add(cb.equal(transaction.get(Transaction_.type), Purchase.class.getSimpleName()));
            break;
        default:
            throw new BusinessException("transaction type not supported");
        }
    }
    if (StringUtils.hasLength(advertiser)) {
        predicates.add(cb.equal(transaction.get(Transaction_.advertiser), advertiser));
    }
    if (StringUtils.hasLength(financial)) {
        predicates.add(cb.like(cb.treat(transaction, Sale.class).get(Sale_.financial), financial));
    }
    if (seller != null) {
        predicates.add(cb.equal(transaction.get(Transaction_.seller).get(Seller_.id), seller));
    }
    return (predicates.toArray(new Predicate[predicates.size()]));
}

From source file:com.yunguchang.data.ApplicationRepository.java

public List<TRsDriverinfoEntity> listAllCandidateDrivers(String[] applicationIds, String carId, String keyword,
        Integer offset, Integer limit, PrincipalExt principalExt) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<TRsDriverinfoEntity> cq = cb.createQuery(TRsDriverinfoEntity.class);
    Root<TRsDriverinfoEntity> driverRoot = cq.from(TRsDriverinfoEntity.class);
    Root<TAzCarinfoEntity> carRoot = cq.from(TAzCarinfoEntity.class);
    cq.select(driverRoot);/*ww w .j  a  v  a 2  s  .  c om*/

    Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery = cq.subquery(TBusScheduleCarEntity.class);

    applyOverlapScheduleCarSubquery(overlapScheduleCarSubQuery, applicationIds, carRoot, driverRoot, cb,
            principalExt);

    Subquery<TRsDriverinfoEntity> subqueryLicense = cq.subquery(TRsDriverinfoEntity.class);
    Root<TAzJzRelaEntity> licenseMapping = subqueryLicense.from(TAzJzRelaEntity.class);
    subqueryLicense.select(driverRoot);
    subqueryLicense.where(

            cb.equal(carRoot.get(TAzCarinfoEntity_.xszcx), licenseMapping.get(TAzJzRelaEntity_.xszcx)),
            cb.equal(licenseMapping.get(TAzJzRelaEntity_.jzyq),
                    driverRoot.get(TRsDriverinfoEntity_.drivecartype)));

    Predicate predicate = cb.and(cb.equal(carRoot.get(TAzCarinfoEntity_.id), carId),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.department), carRoot.get(TAzCarinfoEntity_.sysOrg)),
            cb.equal(driverRoot.get(TRsDriverinfoEntity_.enabled), "1"),
            cb.or(cb.exists(subqueryLicense), cb.isNull(driverRoot.get(TRsDriverinfoEntity_.drivecartype))

            ),

            cb.not(cb.exists(overlapScheduleCarSubQuery))

    );

    if (keyword != null) {
        predicate = cb.and(predicate,
                cb.or(cb.like(driverRoot.get(TRsDriverinfoEntity_.drivername), "%" + keyword + "%")));
    }

    cq.where(predicate);
    cq.orderBy(cb
            .asc(cb.function("casttogbk", String.class, cb.trim(driverRoot.get(TRsDriverinfoEntity_.drivername))

    )));
    TypedQuery<TRsDriverinfoEntity> query = em.createQuery(cq);
    if (offset != null) {
        query.setFirstResult(offset);
    }

    if (limit != null) {
        query.setMaxResults(limit);
    }

    return query.getResultList();

}

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

/**
 * TODO: Remove this method once we migrate away from Oracle getStorageUploadStats that uses Oracle specific 'trunc' function.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range/* ww  w  .  j  a va 2 s . c o  m*/
 *
 * @return the upload statistics
 */
private StorageDailyUploadStats getStorageUploadStatsOracle(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);

    // Create paths.
    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, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

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

    grouping.add(truncCreatedOnDateExpression);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(truncCreatedOnDateExpression));

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

    for (Tuple tuple : tuples) {
        StorageDailyUploadStat uploadStat = new StorageDailyUploadStat();
        uploadStats.getStorageDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(
                DmDateUtils.getXMLGregorianCalendarValue(tuple.get(truncCreatedOnDateExpression)));
        uploadStat.setTotalFiles(tuple.get(totalFilesExpression));
        uploadStat.setTotalBytes(tuple.get(totalBytesExpression));
    }

    return uploadStats;
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.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  www .ja va 2s .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(
                DmDateUtils.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.HerdDaoImpl.java

/**
 * TODO: Remove this method once we migrate away from Oracle getStorageUploadStats that uses Oracle specific 'trunc' function.
 *
 * @param storageAlternateKey the storage alternate key
 * @param dateRange the date range// w  ww.  j a v  a  2s.  c om
 *
 * @return the upload statistics
 */
private StorageDailyUploadStats getStorageUploadStatsOracle(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);

    // Create paths.
    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, totalFilesExpression, totalBytesExpression);
    criteria.where(builder.and(storageNameRestriction, createDateRestriction));

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

    grouping.add(truncCreatedOnDateExpression);
    criteria.groupBy(grouping);

    // Create the order by clause.
    criteria.orderBy(builder.asc(truncCreatedOnDateExpression));

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

    for (Tuple tuple : tuples) {
        StorageDailyUploadStat uploadStat = new StorageDailyUploadStat();
        uploadStats.getStorageDailyUploadStats().add(uploadStat);
        uploadStat.setUploadDate(
                HerdDateUtils.getXMLGregorianCalendarValue(tuple.get(truncCreatedOnDateExpression)));
        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//  w w w .  j a  v  a2 s . 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;
}