List of usage examples for javax.persistence.criteria CriteriaBuilder count
Expression<Long> count(Expression<?> x);
From source file:org.easy.criteria.CriteriaComposer.java
/** * @param criteriaBuilder//from ww w . jav a2 s . c om * @param out */ @SuppressWarnings("unchecked") protected void generateHaving(final CriteriaBuilder criteriaBuilder, final List<Predicate> out) { // log.debug("generateHaving :"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(criteriaBuilder); Preconditions.checkNotNull(root); if (_joins != null && _joins.size() > 0) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> joinEntry : allSetJoins) { CriteriaComposer<?> subCriteria = joinEntry.getValue(); if (subCriteria != null) subCriteria.generateHaving(criteriaBuilder, out); } } if (_havings != null) { List<Predicate> andPredicates = new ArrayList<Predicate>(0); List<Predicate> orPredicates = new ArrayList<Predicate>(0); LogicOperator lastOperator = LogicOperator.NONE; for (HavingContainer<E> havingContainer : _havings) { @SuppressWarnings("rawtypes") Expression expression = null; switch (havingContainer.function) { case COUNT: expression = criteriaBuilder.count(root.get(havingContainer.attribute)); break; case AVG: expression = criteriaBuilder.avg(root.get(havingContainer.attribute)); break; case SUM: expression = criteriaBuilder.sum(root.get(havingContainer.attribute)); break; case MAX: expression = criteriaBuilder.max(root.get(havingContainer.attribute)); break; case MIN: expression = criteriaBuilder.min(root.get(havingContainer.attribute)); break; } Predicate predicate = ComparisonOperatorProcessor.process(criteriaBuilder, expression, havingContainer.comparisionOperator, havingContainer.value); if (havingContainer.notOperator != null) predicate = ComparisonOperatorProcessor.negate(criteriaBuilder, predicate); LogicOperator nextOperator = havingContainer.logicOperator; if (nextOperator == LogicOperator.NONE && !nextOperator.equals(lastOperator)) nextOperator = lastOperator; switch (nextOperator) { case AND: case NONE: andPredicates.add(predicate); break; case OR: orPredicates.add(predicate); break; default: throw new java.lang.IllegalStateException( "Unknown operator found " + havingContainer.comparisionOperator.toString()); } lastOperator = nextOperator; } // end for if (andPredicates != null && andPredicates.size() > 0) out.add(criteriaBuilder.and(andPredicates.toArray(new Predicate[andPredicates.size()]))); if (orPredicates != null && orPredicates.size() > 0) out.add(criteriaBuilder.or(orPredicates.toArray(new Predicate[orPredicates.size()]))); } // end if }
From source file:org.easy.criteria.CriteriaComposer.java
/** * @param out//from w ww . j ava2s.c o m */ @SuppressWarnings("unchecked") protected void generateSelect(final CriteriaBuilder criteriaBuilder, final List<Selection<?>> out) { Preconditions.checkNotNull(out); if (multiselect != null && multiselect.size() > 0) { out.addAll(multiselect); } if (_selects != null && _selects.size() > 0) { for (SelectContainer<E> selectContainer : _selects) { if (selectContainer.function == null) { Selection<?> selection = root.get(selectContainer.singularAttribute); selection.alias(selectContainer.alias); out.add(selection); } else { @SuppressWarnings("rawtypes") Expression numExp = null; switch (selectContainer.function) { case COUNT: numExp = criteriaBuilder.count(root.get(selectContainer.singularAttribute)); numExp.alias(selectContainer.alias); break; case AVG: numExp = criteriaBuilder.avg(root.get(selectContainer.singularAttribute)); numExp.alias(selectContainer.alias); break; case SUM: numExp = criteriaBuilder.sum(root.get(selectContainer.singularAttribute)); numExp.alias(selectContainer.alias); break; case MAX: numExp = criteriaBuilder.max(root.get(selectContainer.singularAttribute)); numExp.alias(selectContainer.alias); break; case MIN: numExp = criteriaBuilder.min(root.get(selectContainer.singularAttribute)); numExp.alias(selectContainer.alias); break; } if (numExp != null) out.add(numExp); } } } if (_joins != null) { Set<Entry<JoinContainer<E>, CriteriaComposer<?>>> allSetJoins = _joins.entrySet(); for (Entry<JoinContainer<E>, CriteriaComposer<?>> join : allSetJoins) { CriteriaComposer<?> subCriteria = join.getValue(); if (subCriteria != null) subCriteria.generateSelect(criteriaBuilder, out); } } }
From source file:org.easy.criteria.CriteriaProcessor.java
/** * Counts the result found for the given criteria * //w w w . j a va 2 s . c om * @param criteria * @param distinct * @return */ public <T> long count(final CriteriaComposer<T> criteria, boolean distinct) { log.trace("CriteriaProcessor.count"); Preconditions.checkNotNull(criteria); Class<T> forClass = criteria.getEntityClass(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class); Root<T> root = criteriaQuery.from(forClass); log.debug("root =" + forClass.getName()); if (distinct) criteriaQuery.select(criteriaBuilder.countDistinct(root)); else criteriaQuery.select(criteriaBuilder.count(root)); List<Predicate> predicates = new ArrayList<Predicate>(); if (criteria != null) { criteria.generateJoins(root); criteria.generateWhere(criteriaBuilder, predicates); } criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery<Long> query = entityManager.createQuery(criteriaQuery); long result = query.getSingleResult(); log.debug("CriteriaProcessor.count =" + result); return result; }
From source file:org.eclipse.jubula.client.core.persistence.TestResultPM.java
/** * @param session/*from w ww.j a v a 2 s. com*/ * The session in which to execute the Persistence (JPA / * EclipseLink) query. * @param summaryId * The database ID of the summary for which to compute the * corresponding Test Result nodes. * @return the Test Result nodes associated with the given Test Result * Summary, sorted by sequence (ascending). */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static boolean hasTestResultDetails(EntityManager session, Long summaryId) { boolean hasDetails = false; if (session == null) { return hasDetails; } CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery query = builder.createQuery(); Root from = query.from(PoMaker.getTestResultClass()); query.select(builder.count(from)).where(builder.equal(from.get("internalTestResultSummaryID"), summaryId)); //$NON-NLS-1$ Number result = (Number) session.createQuery(query).getSingleResult(); if (result.longValue() > 0) { hasDetails = true; } return hasDetails; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}//from w w w.j av a 2 s . co m */ @Override public Long getBusinessObjectFormatCount(PartitionKeyGroupEntity partitionKeyGroupEntity) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The criteria root is the business object format. Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria .from(BusinessObjectFormatEntity.class); // Create path. Expression<Long> businessObjectFormatCount = builder .count(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.id)); // Create the standard restrictions (i.e. the standard where clauses). Predicate partitionKeyGroupRestriction = builder.equal( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.partitionKeyGroup), partitionKeyGroupEntity); criteria.select(businessObjectFormatCount).where(partitionKeyGroupRestriction); return entityManager.createQuery(criteria).getSingleResult(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}// w w w.j a v a 2 s . c o m */ @Override public Long getBusinessObjectDataCount(BusinessObjectFormatKey businessObjectFormatKey) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.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, 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); // Create path. Expression<Long> businessObjectDataCount = builder .count(businessObjectDataEntity.get(BusinessObjectDataEntity_.id)); // Create the standard restrictions (i.e. the standard where clauses). Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectFormatKey.getNamespace().toUpperCase()); queryRestriction = builder.and(queryRestriction, builder.equal( builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)), businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)), businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectFormatKey.getBusinessObjectFormatFileType().toUpperCase())); queryRestriction = builder.and(queryRestriction, builder.equal( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion), businessObjectFormatKey.getBusinessObjectFormatVersion())); criteria.select(businessObjectDataCount).where(queryRestriction); return entityManager.createQuery(criteria).getSingleResult(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}/*from w w w . ja va 2s . c o m*/ */ @Override public Long getStorageFileCount(String storageName, String filePathPrefix) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteria = builder.createQuery(Long.class); // The criteria root is the storage files. 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 path. Expression<Long> storageFileCount = builder.count(storageFileEntity.get(StorageFileEntity_.id)); // Create the standard restrictions (i.e. the standard where clauses). Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase()); Predicate filePathRestriction = builder.like(storageFileEntity.get(StorageFileEntity_.path), String.format("%s%%", filePathPrefix)); // Add the clauses for the query. criteria.select(storageFileCount).where(builder.and(storageNameRestriction, filePathRestriction)); return entityManager.createQuery(criteria).getSingleResult(); }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * TODO: Make this method the main body of getStorageUploadStats once we migrate away from Oracle getStorageUploadStats TODO: that leverages the storage * file view to query. This method is meant to be database agnostic. * * @param storageAlternateKey the storage alternate key * @param dateRange the date range/*ww w.java 2s . co m*/ * * @return the upload statistics */ private StorageDailyUploadStats getStorageUploadStatsDatabaseAgnostic( StorageAlternateKeyDto storageAlternateKey, DateRangeDto dateRange) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); Root<StorageFileViewEntity> storageFileViewEntity = criteria.from(StorageFileViewEntity.class); 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, totalFilesExpression, totalBytesExpression); criteria.where(builder.and(storageNameRestriction, createDateRestriction)); List<Expression<?>> grouping = new ArrayList<>(); grouping.add(createdDate); criteria.groupBy(grouping); criteria.orderBy(builder.asc(createdDate)); // 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(createdDate))); 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 getStorageUploadStats that uses Oracle specific 'trunc' function. * * @param storageAlternateKey the storage alternate key * @param dateRange the date range//from ww w .j a v a2 s .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( 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: 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 www. ja va2 s . c o 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(DmDateUtils.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; }