List of usage examples for javax.persistence.criteria CriteriaBuilder desc
Order desc(Expression<?> x);
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
@SuppressWarnings("unchecked") public <T extends IBean> T[] findByValues(Class<T> beansInterface, Map<String, Object> values, String orderBy, boolean ascending) { // validate entity manager transaction if (entityManager == null) { throw new IllegalStateException("Transaction not initiated or already closed"); }/*from w w w. j a v a2s . co m*/ // validate bean interface Class<? extends IBean> beanClass = BEAN_INTERFACE_TO_CLASS_MAP.get(beansInterface); if (beanClass == null) { throw new IllegalArgumentException("Invalid bean interface specified"); } // get persistent beans by criteria try { // construct query criteria CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<? extends IBean> criteriaQuery = criteriaBuilder.createQuery(beanClass); Root<? extends IBean> beanRoot = criteriaQuery.from(beanClass); if ((values != null) && !values.isEmpty()) { Predicate predicate = null; for (Map.Entry<String, Object> value : values.entrySet()) { Predicate valuePredicate = ((value.getValue() != null) ? criteriaBuilder.equal(beanRoot.get(value.getKey()), value.getValue()) : criteriaBuilder.isNull(beanRoot.get(value.getKey()))); predicate = ((predicate != null) ? criteriaBuilder.and(predicate, valuePredicate) : valuePredicate); } criteriaQuery.where(predicate); } if (orderBy != null) { criteriaQuery.orderBy(ascending ? criteriaBuilder.asc(beanRoot.get(orderBy)) : criteriaBuilder.desc(beanRoot.get(orderBy))); } // invoke query Query query = entityManager.createQuery(criteriaQuery); List<? extends IBean> beansList = query.getResultList(); if ((beansList != null) && !beansList.isEmpty()) { return beansList.toArray((T[]) Array.newInstance(beansInterface, beansList.size())); } } catch (Exception e) { logger.error("Unexpected exception: " + e, e); } return (T[]) Array.newInstance(beansInterface, 0); }
From source file:org.broadleafcommerce.core.catalog.dao.IndexFieldCustomPersistenceHandler.java
@Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { FilterAndSortCriteria fieldFsc = cto.getCriteriaMap().get("field"); if (fieldFsc != null) { List<String> filterValues = fieldFsc.getFilterValues(); boolean didFilter = false; cto.getCriteriaMap().remove("field"); CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder(); CriteriaQuery<IndexField> criteria = builder.createQuery(IndexField.class); Root<IndexFieldImpl> root = criteria.from(IndexFieldImpl.class); criteria.select(root);// ww w . j a v a 2s. c o m // Check if we are searching for specific field names List<Predicate> restrictions = new ArrayList<Predicate>(); if (CollectionUtils.isNotEmpty(filterValues)) { restrictions.add(builder.like(root.get("field").<String>get("friendlyName"), "%" + filterValues.get(0) + "%")); didFilter = true; } // Check if this filter value has a sort direction associated with it Order order = null; for (FilterAndSortCriteria sortCriteria : cto.getCriteriaMap().values()) { if (sortCriteria.getSortDirection() != null) { Path path = root; try { // Try to find the path to the property in IndexFieldImpl String[] pathParts = sortCriteria.getPropertyId().split("\\."); for (String part : pathParts) { path = path.get(part); } // If we made it here, we have the path, set the sorting (asc/desc) if (sortCriteria.getSortAscending()) { order = builder.asc(path); } else { order = builder.desc(path); } criteria.orderBy(order); break; } catch (IllegalArgumentException e) { // This isn't an actual entity property continue; } } } criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); TypedQuery<IndexField> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria); List<IndexField> indexFields = query.getResultList(); // Convert the result list into a list of entities PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Map<String, FieldMetadata> indexFieldMetadata = helper .getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); Entity[] entities = helper.getRecords(indexFieldMetadata, indexFields); // We need to get the total number of records available because the entityList returned may not be the full set. Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective); List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto, IndexField.class.getName(), originalProps); int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(), filterMappings); // Create a Dynamic Result Set from the entity list created above. DynamicResultSet resultSet = new DynamicResultSet(entities, (didFilter ? entities.length : totalRecords)); return resultSet; } DynamicResultSet resultSet = helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto); return resultSet; }
From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java
protected void attachOrderBy(SearchCriteria searchCriteria, From<?, ? extends Product> product, Path<? extends Sku> sku, CriteriaQuery<?> criteria) { if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) { CriteriaBuilder builder = em.getCriteriaBuilder(); List<Order> sorts = new ArrayList<Order>(); String sortQueries = searchCriteria.getSortQuery(); for (String sortQuery : sortQueries.split(",")) { String[] sort = sortQuery.split(" "); if (sort.length == 2) { String key = sort[0]; boolean asc = sort[1].toLowerCase().contains("asc"); // Determine whether we should use the product path or the sku path Path<?> pathToUse; if (key.contains("defaultSku.")) { pathToUse = sku;//from w ww .j a va2 s.c o m key = key.substring("defaultSku.".length()); } else if (key.contains("product.")) { pathToUse = product; key = key.substring("product.".length()); } else { // We don't know which path this facet is built on - resolves previous bug that attempted // to attach search facet to any query parameter continue; } if (asc) { sorts.add(builder.asc(pathToUse.get(key))); } else { sorts.add(builder.desc(pathToUse.get(key))); } } } criteria.orderBy(sorts.toArray(new Order[sorts.size()])); } }
From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.CriteriaTranslatorImpl.java
protected void addSorting(CriteriaBuilder criteriaBuilder, List<Order> sorts, FilterMapping filterMapping, Path path) {/*from ww w . j a v a2 s .co m*/ Expression exp = path; if (filterMapping.getNullsLast() != null && filterMapping.getNullsLast()) { Object largeValue = getAppropriateLargeSortingValue(path.getJavaType()); if (largeValue != null) { exp = criteriaBuilder.coalesce(path, largeValue); } } if (SortDirection.ASCENDING == filterMapping.getSortDirection()) { sorts.add(criteriaBuilder.asc(exp)); } else { sorts.add(criteriaBuilder.desc(exp)); } }
From source file:org.easy.criteria.CriteriaComposer.java
/** * @param criteriaBuilder//w ww .j a v a 2 s .co m * @param out */ @SuppressWarnings("unchecked") protected void generateOrderBy(final CriteriaBuilder criteriaBuilder, Map<Integer, Order> out) { log.trace("generateOrderBy"); Preconditions.checkNotNull(out); Preconditions.checkNotNull(root); Preconditions.checkNotNull(criteriaBuilder); // First others 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.generateOrderBy(criteriaBuilder, out); } } // Then me. I will overwrite rank of others. if (_orderBys != null && _orderBys.size() > 0) { for (OrderByContainer<E> orderByContainer : _orderBys) { boolean ascending = orderByContainer.ascending; if (ascending) { if (log.isDebugEnabled()) log.debug("ascending _orderBy " + orderByContainer.attribute.getName()); out.put(orderByContainer.rank, criteriaBuilder.asc(root.get(orderByContainer.attribute))); } else { if (log.isDebugEnabled()) log.debug("descending _orderBy " + orderByContainer.attribute.getName()); out.put(orderByContainer.rank, criteriaBuilder.desc(root.get(orderByContainer.attribute))); } } } }
From source file:org.eclipse.hawkbit.repository.jpa.JpaTargetManagement.java
@Override public Slice<Target> findTargetsAllOrderByLinkedDistributionSet(final Pageable pageable, final Long orderByDistributionId, final FilterParams filterParams) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<JpaTarget> query = cb.createQuery(JpaTarget.class); final Root<JpaTarget> targetRoot = query.from(JpaTarget.class); // select case expression to retrieve the case value as a column to be // able to order based on // this column, installed first,... final Expression<Object> selectCase = cb.selectCase() .when(cb.equal(targetRoot.get(JpaTarget_.installedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 1) .when(cb.equal(targetRoot.get(JpaTarget_.assignedDistributionSet).get(JpaDistributionSet_.id), orderByDistributionId), 2) .otherwise(100);//from w w w . j ava 2 s . co m // multiselect statement order by the select case and controllerId query.distinct(true); // build the specifications and then to predicates necessary by the // given filters final Predicate[] specificationsForMultiSelect = specificationsToPredicate( buildSpecificationList(filterParams), targetRoot, query, cb); // if we have some predicates then add it to the where clause of the // multiselect if (specificationsForMultiSelect.length > 0) { query.where(specificationsForMultiSelect); } // add the order to the multi select first based on the selectCase query.orderBy(cb.asc(selectCase), cb.desc(targetRoot.get(JpaTarget_.id))); // the result is a Object[] due the fact that the selectCase is an extra // column, so it cannot // be mapped directly to a Target entity because the selectCase is not a // attribute of the // Target entity, the the Object array contains the Target on the first // index (case of the // multiselect order) of the array and // the 2nd contains the selectCase int value. final int pageSize = pageable.getPageSize(); final List<JpaTarget> resultList = entityManager.createQuery(query).setFirstResult(pageable.getOffset()) .setMaxResults(pageSize + 1).getResultList(); final boolean hasNext = resultList.size() > pageSize; return new SliceImpl<>(Collections.unmodifiableList(resultList), pageable, hasNext); }
From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java
public TypedQuery<Connection> buildLastConnections() { EntityManager em = EntityManagerHolder.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class); Root<Connection> connection = criteria.from(Connection.class); Predicate predicate = null;// w w w . j a v a 2 s .com //owner if (this.owner != null) { predicate = cb.equal(connection.get(Connection_.senderId), owner.getId()); } //status if (this.status != null) { predicate = cb.and(predicate, cb.equal(connection.get(Connection_.status), this.status)); } CriteriaQuery<Connection> select = criteria.select(connection).distinct(true); select.where(predicate); select.orderBy(cb.desc(connection.<Long>get(Connection_.id))); TypedQuery<Connection> typedQuery = em.createQuery(select); if (this.limit > 0) { typedQuery.setFirstResult((int) offset); typedQuery.setMaxResults((int) limit); } return typedQuery; }
From source file:org.finra.dm.dao.impl.DmDaoImpl.java
/** * {@inheritDoc}/*from w w w . j a v a2 s.c om*/ */ @Override public ExpectedPartitionValueEntity getExpectedPartitionValue( ExpectedPartitionValueKey expectedPartitionValueKey, int offset) { // Create the criteria builder and the criteria. CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<ExpectedPartitionValueEntity> criteria = builder .createQuery(ExpectedPartitionValueEntity.class); // The criteria root is the expected partition value. Root<ExpectedPartitionValueEntity> expectedPartitionValueEntity = criteria .from(ExpectedPartitionValueEntity.class); // Join to the other tables we can filter on. Join<ExpectedPartitionValueEntity, PartitionKeyGroupEntity> partitionKeyGroupEntity = expectedPartitionValueEntity .join(ExpectedPartitionValueEntity_.partitionKeyGroup); // Add a restriction to filter case insensitive groups that match the user specified group. Predicate whereRestriction = builder.equal( builder.upper(partitionKeyGroupEntity.get(PartitionKeyGroupEntity_.partitionKeyGroupName)), expectedPartitionValueKey.getPartitionKeyGroupName().toUpperCase()); // Depending on the offset, we might need to order the records in the query. Order orderByExpectedPartitionValue = null; // Add additional restrictions to handle expected partition value and an optional offset. if (offset == 0) { // Since there is no offset, we need to match the expected partition value exactly. whereRestriction = builder.and(whereRestriction, builder.equal(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue), expectedPartitionValueKey.getExpectedPartitionValue())); } else if (offset > 0) { // For a positive offset value, add a restriction to filter expected partition values that are >= the user specified expected partition value. whereRestriction = builder.and(whereRestriction, builder.greaterThanOrEqualTo( expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue), expectedPartitionValueKey.getExpectedPartitionValue())); // Order by expected partition value in ascending order. orderByExpectedPartitionValue = builder .asc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue)); } else { // For a negative offset value, add a restriction to filter expected partition values that are <= the user specified expected partition value. whereRestriction = builder.and(whereRestriction, builder.lessThanOrEqualTo( expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue), expectedPartitionValueKey.getExpectedPartitionValue())); // Order by expected partition value in descending order. orderByExpectedPartitionValue = builder .desc(expectedPartitionValueEntity.get(ExpectedPartitionValueEntity_.partitionValue)); } // Add the clauses for the query and execute the query. if (offset == 0) { criteria.select(expectedPartitionValueEntity).where(whereRestriction); return executeSingleResultQuery(criteria, String.format( "Found more than one expected partition value with parameters {partitionKeyGroupName=\"%s\", expectedPartitionValue=\"%s\"}.", expectedPartitionValueKey.getPartitionKeyGroupName(), expectedPartitionValueKey.getExpectedPartitionValue())); } else { criteria.select(expectedPartitionValueEntity).where(whereRestriction) .orderBy(orderByExpectedPartitionValue); List<ExpectedPartitionValueEntity> resultList = entityManager.createQuery(criteria) .setFirstResult(Math.abs(offset)).setMaxResults(1).getResultList(); return resultList.size() > 0 ? resultList.get(0) : null; } }
From source file:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java
/** * Create search restrictions./*from ww w . j av a 2 s.c o m*/ * * @param builder the criteria builder * @param criteria the criteria * @param businessObjectDataEntity the root business object data entity * @param businessObjectDataSearchKey the business object data search key * @param namespaceEntity the namespace entity * @param fileTypeEntity the file type entity * @param isCountQuery specifies if this is a count query * * @return the search restrictions */ private Predicate getPredict(CriteriaBuilder builder, CriteriaQuery<?> criteria, Root<BusinessObjectDataEntity> businessObjectDataEntity, BusinessObjectDataSearchKey businessObjectDataSearchKey, NamespaceEntity namespaceEntity, FileTypeEntity fileTypeEntity, boolean isCountQuery) { // Join to the other tables we can filter on. Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = businessObjectDataEntity .join(BusinessObjectDataEntity_.businessObjectFormat); Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity .join(BusinessObjectFormatEntity_.businessObjectDefinition); if (!isCountQuery) { List<Order> orderList = new ArrayList<>(); orderList.add( builder.asc(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.namespace))); orderList.add(builder.asc(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name))); orderList.add(builder.asc(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage))); orderList.add(builder.asc(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.fileType))); orderList.add(builder .desc(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue2))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue3))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue4))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.partitionValue5))); orderList.add(builder.desc(businessObjectDataEntity.get(BusinessObjectDataEntity_.version))); criteria.orderBy(orderList); } // Create the standard restrictions based on the business object search key values (i.e. the standard where clauses). // Create a restriction on namespace code. Predicate predicate = builder.equal( businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.namespace), namespaceEntity); // Create and append a restriction on business object definition name. predicate = builder.and(predicate, builder.equal( builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)), businessObjectDataSearchKey.getBusinessObjectDefinitionName().toUpperCase())); // Create and append a restriction on business object format usage. if (!StringUtils.isEmpty(businessObjectDataSearchKey.getBusinessObjectFormatUsage())) { predicate = builder.and(predicate, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)), businessObjectDataSearchKey.getBusinessObjectFormatUsage().toUpperCase())); } // If specified, create and append a restriction on business object format file type. if (fileTypeEntity != null) { predicate = builder.and(predicate, builder .equal(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.fileType), fileTypeEntity)); } // If specified, create and append a restriction on business object format version. if (businessObjectDataSearchKey.getBusinessObjectFormatVersion() != null) { predicate = builder.and(predicate, builder.equal( businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion), businessObjectDataSearchKey.getBusinessObjectFormatVersion())); } predicate = createPartitionValueFilters(businessObjectDataSearchKey, businessObjectDataEntity, businessObjectFormatEntity, builder, predicate); List<AttributeValueFilter> attributeValueFilters = businessObjectDataSearchKey.getAttributeValueFilters(); if (attributeValueFilters != null && !attributeValueFilters.isEmpty()) { predicate = applyAttributeValueFilters(businessObjectDataSearchKey, businessObjectDataEntity, builder, predicate); } // Apply registration date range filter, if specified. if (businessObjectDataSearchKey.getRegistrationDateRangeFilter() != null) { predicate = applyRegistrationDateRangeFilter( businessObjectDataSearchKey.getRegistrationDateRangeFilter(), businessObjectDataEntity, builder, predicate); } if (BooleanUtils.isTrue(businessObjectDataSearchKey.isFilterOnLatestValidVersion())) { String validStatus = BusinessObjectDataStatusEntity.VALID; Subquery<Integer> subQuery = getMaximumBusinessObjectDataVersionSubQuery(builder, criteria, businessObjectDataEntity, businessObjectFormatEntity, validStatus); predicate = builder.and(predicate, builder.in(businessObjectDataEntity.get(BusinessObjectDataEntity_.version)).value(subQuery)); } if (BooleanUtils.isTrue(businessObjectDataSearchKey.isFilterOnRetentionExpiration())) { predicate = applyRetentionExpirationFilter(businessObjectDataSearchKey, businessObjectDataEntity, businessObjectFormatEntity, builder, predicate); } return predicate; }
From source file:org.finra.herd.dao.impl.BusinessObjectDataDaoImpl.java
@Override public List<BusinessObjectDataKey> getBusinessObjectDataByBusinessObjectDefinition( BusinessObjectDefinitionEntity businessObjectDefinitionEntity, Integer maxResults) { // Get ids for all business object formats registered with the specified business object definition. List<Integer> businessObjectFormatIds = businessObjectFormatDao .getBusinessObjectFormatIdsByBusinessObjectDefinition(businessObjectDefinitionEntity); // Return no results if the business object definition has no business object formats registered with it. if (CollectionUtils.isEmpty(businessObjectFormatIds)) { return new ArrayList<>(); }/*from w w w . ja va 2 s . c o m*/ // 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> businessObjectDataEntityRoot = criteria.from(BusinessObjectDataEntity.class); // Create the standard restrictions (i.e. the standard where clauses). Predicate predicate = getPredicateForInClause(builder, businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.businessObjectFormatId), businessObjectFormatIds); // Build an order by clause. List<Order> orderBy = new ArrayList<>(); for (SingularAttribute<BusinessObjectDataEntity, String> businessObjectDataPartition : BUSINESS_OBJECT_DATA_PARTITIONS) { orderBy.add(builder.desc(businessObjectDataEntityRoot.get(businessObjectDataPartition))); } orderBy.add(builder.desc(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.version))); // Add the clauses for the query. criteria.select(businessObjectDataEntityRoot).where(predicate).orderBy(orderBy); // Create a query. TypedQuery<BusinessObjectDataEntity> query = entityManager.createQuery(criteria); // If specified, set the maximum number of results for query to return. if (maxResults != null) { query.setMaxResults(maxResults); } // Run the query to get a list of entities back. List<BusinessObjectDataEntity> businessObjectDataEntities = query.getResultList(); // Populate the "keys" objects from the returned entities. List<BusinessObjectDataKey> businessObjectDataKeys = new ArrayList<>(); for (BusinessObjectDataEntity businessObjectDataEntity : businessObjectDataEntities) { BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(); businessObjectDataKeys.add(businessObjectDataKey); businessObjectDataKey.setNamespace(businessObjectDataEntity.getBusinessObjectFormat() .getBusinessObjectDefinition().getNamespace().getCode()); businessObjectDataKey.setBusinessObjectDefinitionName( businessObjectDataEntity.getBusinessObjectFormat().getBusinessObjectDefinition().getName()); businessObjectDataKey .setBusinessObjectFormatUsage(businessObjectDataEntity.getBusinessObjectFormat().getUsage()); businessObjectDataKey.setBusinessObjectFormatFileType( businessObjectDataEntity.getBusinessObjectFormat().getFileType().getCode()); businessObjectDataKey.setBusinessObjectFormatVersion( businessObjectDataEntity.getBusinessObjectFormat().getBusinessObjectFormatVersion()); businessObjectDataKey.setPartitionValue(businessObjectDataEntity.getPartitionValue()); businessObjectDataKey.setSubPartitionValues(getSubPartitionValues(businessObjectDataEntity)); businessObjectDataKey.setBusinessObjectDataVersion(businessObjectDataEntity.getVersion()); } return businessObjectDataKeys; }