Example usage for javax.persistence.criteria CriteriaBuilder asc

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

Introduction

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

Prototype

Order asc(Expression<?> x);

Source Link

Document

Create an ordering by the ascending value of the expression.

Usage

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) {//w ww  .j av  a2s  .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/*from   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);/*www.j  a  v  a2s.  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.eclipse.jubula.client.core.persistence.TestResultPM.java

/**
 * @param session 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).
 *//*  w ww . j  a  v  a  2s  .  c o  m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<ITestResultPO> computeTestResultListForSummary(EntityManager session, Long summaryId) {

    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery query = builder.createQuery();
    Root from = query.from(PoMaker.getTestResultClass());
    query.orderBy(builder.asc(from.get("keywordSequence"))) //$NON-NLS-1$
            .select(from).where(builder.equal(from.get("internalTestResultSummaryID"), summaryId)); //$NON-NLS-1$

    return session.createQuery(query).getResultList();
}

From source file:org.exoplatform.social.addons.storage.dao.jpa.query.RelationshipQueryBuilder.java

public TypedQuery<Connection> buildFilter() {
    EntityManager em = EntityManagerHolder.get();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Connection> criteria = cb.createQuery(Connection.class);
    Root<Connection> connection = criteria.from(Connection.class);
    Join<Connection, Profile> receiver = connection.join(Connection_.receiver);
    ///*from  w w w. j  a  va2s. com*/
    CriteriaQuery<Connection> select = criteria.select(connection);
    select.where(buildPredicateFilter(cb, receiver, connection));
    select.orderBy(cb.asc(receiver.get(Profile_.fullName)));
    //
    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}//  www  . j  a  va 2s .c  o m
 */
@Override
public List<NamespaceKey> getNamespaces() {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the business object definition.
    Root<NamespaceEntity> namespaceEntity = criteria.from(NamespaceEntity.class);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);

    // Add the select clause.
    criteria.select(namespaceCodeColumn);

    // Add the order by clause.
    criteria.orderBy(builder.asc(namespaceCodeColumn));

    // Run the query to get a list of namespace codes back.
    List<String> namespaceCodes = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned namespace codes.
    List<NamespaceKey> namespaceKeys = new ArrayList<>();
    for (String namespaceCode : namespaceCodes) {
        namespaceKeys.add(new NamespaceKey(namespaceCode));
    }

    return namespaceKeys;
}

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

/**
 * {@inheritDoc}/*from  ww w.  j  av  a2 s .co  m*/
 */
@Override
public List<BusinessObjectDefinitionKey> getBusinessObjectDefinitions(String namespaceCode) {
    // 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 definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = criteria
            .from(BusinessObjectDefinitionEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn);

    // If namespace code is specified, add the where clause.
    if (StringUtils.isNotBlank(namespaceCode)) {
        criteria.where(builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
                namespaceCode.toUpperCase()));
    }

    // Add the order by clause.
    if (StringUtils.isNotBlank(namespaceCode)) {
        criteria.orderBy(builder.asc(namespaceCodeColumn), builder.asc(businessObjectDefinitionNameColumn));
    } else {
        criteria.orderBy(builder.asc(businessObjectDefinitionNameColumn));
    }

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

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectDefinitionKey> businessObjectDefinitionKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey();
        businessObjectDefinitionKeys.add(businessObjectDefinitionKey);
        businessObjectDefinitionKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectDefinitionKey
                .setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
    }

    return businessObjectDefinitionKeys;
}

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

/**
 * {@inheritDoc}//from  ww w.ja v a  2s . c  o m
 */
@Override
public List<FileTypeKey> getFileTypes() {
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<String> criteria = builder.createQuery(String.class);

    // The criteria root is the file type.
    Root<FileTypeEntity> fileTypeEntity = criteria.from(FileTypeEntity.class);

    // Get the columns.
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);

    // Add the select clause.
    criteria.select(fileTypeCodeColumn);

    // Add the order by clause.
    criteria.orderBy(builder.asc(fileTypeCodeColumn));

    // Run the query to get a list of file type codes back.
    List<String> fileTypeCodes = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned file type codes.
    List<FileTypeKey> fileTypeKeys = new ArrayList<>();
    for (String fileTypeCode : fileTypeCodes) {
        fileTypeKeys.add(new FileTypeKey(fileTypeCode));
    }

    return fileTypeKeys;
}

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

/**
 * {@inheritDoc}//from w  w  w  .j a va2  s  . c  o m
 */
@Override
public List<BusinessObjectFormatKey> getBusinessObjectFormats(
        BusinessObjectDefinitionKey businessObjectDefinitionKey, boolean latestBusinessObjectFormatVersion) {
    // 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 format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria
            .from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity
            .join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity
            .join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity
            .get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity
            .get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Expression<Integer> maxBusinessObjectFormatVersionExpression = builder
            .max(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)),
            businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction,
            builder.equal(
                    builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
                    businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn,
            businessObjectFormatUsageColumn, fileTypeCodeColumn,
            latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                    : businessObjectFormatVersionColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // If only the latest (maximum) business object format versions to be returned, create and apply the group by clause.
    if (latestBusinessObjectFormatVersion) {
        List<Expression<?>> grouping = new ArrayList<>();
        grouping.add(namespaceCodeColumn);
        grouping.add(businessObjectDefinitionNameColumn);
        grouping.add(businessObjectFormatUsageColumn);
        grouping.add(fileTypeCodeColumn);
        criteria.groupBy(grouping);
    }

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatUsageColumn));
    orderBy.add(builder.asc(fileTypeCodeColumn));
    if (!latestBusinessObjectFormatVersion) {
        orderBy.add(builder.asc(businessObjectFormatVersionColumn));
    }
    criteria.orderBy(orderBy);

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

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectFormatKey> businessObjectFormatKeys = new ArrayList<>();
    for (Tuple tuple : tuples) {
        BusinessObjectFormatKey businessObjectFormatKey = new BusinessObjectFormatKey();
        businessObjectFormatKeys.add(businessObjectFormatKey);
        businessObjectFormatKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectFormatKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        businessObjectFormatKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        businessObjectFormatKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        businessObjectFormatKey.setBusinessObjectFormatVersion(
                tuple.get(latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression
                        : businessObjectFormatVersionColumn));
    }

    return businessObjectFormatKeys;
}

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

/**
 * {@inheritDoc}// ww  w  .j  av a 2  s.  c  o m
 */
@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;
    }
}