javax.persistence.criteria.CriteriaQuery.orderBy()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(139)

本文整理了Java中javax.persistence.criteria.CriteriaQuery.orderBy()方法的一些代码示例,展示了CriteriaQuery.orderBy()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CriteriaQuery.orderBy()方法的具体详情如下:
包路径:javax.persistence.criteria.CriteriaQuery
类名称:CriteriaQuery
方法名:orderBy

CriteriaQuery.orderBy介绍

[英]Specify the ordering expressions that are used to order the query results. Replaces the previous ordering expressions, if any. If no ordering expressions are specified, the previous ordering, if any, is simply removed, and results will be returned in no particular order. The order of the ordering expressions in the list determines the precedence, whereby the first element in the list has highest precedence.
[中]指定用于对查询结果进行排序的排序表达式。替换以前的排序表达式(如果有)。如果未指定排序表达式,则只需删除以前的排序(如果有),结果将不按特定顺序返回。列表中排序表达式的顺序决定了优先级,因此列表中的第一个元素具有最高优先级。

代码示例

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
public List<Long> readAllGenericEntityId(Class<?> clazz) {
  clazz = DynamicDaoHelperImpl.getNonProxyImplementationClassIfNecessary(clazz);
  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<Long> criteria = builder.createQuery(Long.class);
  Root root = criteria.from(clazz);
  criteria.select(root.get(getIdField(clazz).getName()).as(Long.class));
  criteria.orderBy(builder.asc(root.get(getIdField(clazz).getName())));
  return em.createQuery(criteria).getResultList();
}

代码示例来源:origin: spring-projects/spring-data-jpa

/**
 * Creates a {@link TypedQuery} for the given {@link Specification} and {@link Sort}.
 *
 * @param spec can be {@literal null}.
 * @param domainClass must not be {@literal null}.
 * @param sort must not be {@literal null}.
 * @return
 */
protected <S extends T> TypedQuery<S> getQuery(@Nullable Specification<S> spec, Class<S> domainClass, Sort sort) {
  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<S> query = builder.createQuery(domainClass);
  Root<S> root = applySpecificationToCriteria(spec, domainClass, query);
  query.select(root);
  if (sort.isSorted()) {
    query.orderBy(toOrders(sort, root, builder));
  }
  return applyRepositoryMethodMetadata(em.createQuery(query));
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected void attachOrderBy(SearchCriteria searchCriteria, 
    From<?, ? extends Product> product, Path<? extends Sku> sku, CriteriaQuery<?> criteria) {
  if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
    CriteriaBuilder builder = em.getCriteriaBuilder();
          sorts.add(builder.asc(pathToUse.get(key)));
        } else {
          sorts.add(builder.desc(pathToUse.get(key)));
    criteria.orderBy(sorts.toArray(new Order[sorts.size()]));

代码示例来源:origin: de.adorsys.psd2/consent-management-lib

private Specification<EventEntity> eventPeriodSpecification(OffsetDateTime start, OffsetDateTime end) {
    return (root, criteriaQuery, criteriaBuilder) -> {
      criteriaQuery.orderBy(criteriaBuilder.asc(root.get(TIMESTAMP_ID_ATTRIBUTE)));
      return criteriaBuilder.between(root.get(TIMESTAMP_ID_ATTRIBUTE), start, end);
    };
  }
}

代码示例来源:origin: liimaorg/liima

/**
 * @return a list containing all release entities ordered by installationInProductionAt
 */
public List<ReleaseEntity> loadAllReleaseEntities(boolean sortDesc) {
  CriteriaQuery<ReleaseEntity> query = entityManager.getCriteriaBuilder().createQuery(ReleaseEntity.class);
  Root<ReleaseEntity> root = query.from(ReleaseEntity.class);
  query.orderBy(getDefaultOrder(root, sortDesc));
  return entityManager.createQuery(query).getResultList();
}

代码示例来源:origin: zstackio/zstack

private void done() {
  if (_selects.size() == 0) {
    _query = _builder.createQuery(_entityClass);
  } else if (_selects.size() == 1) {
    Class<?> selectType = _selects.get(0)._javaType;
    _query = _builder.createQuery(selectType);
  } else {
    _query = _builder.createTupleQuery(); 
  }
  
  _root = _query.from(_entityClass);
  
  if (_selects.size() == 0) {
  } else if (_selects.size() == 1) {
    Path p = _root.get(_selects.get(0)._attr);
    _query.select(p);
  } else {
    for (AttrInfo info : _selects) {
      _paths.add(_root.get(info._attr)); 
    }
    _query.multiselect(_paths);
  }
  _query.where(whereClause());
  _query.orderBy(orderClause());
  groupByClause(_query);
}

代码示例来源:origin: jamesagnew/hapi-fhir

outerQuery.multiselect(myBuilder.countDistinct(myResourceTableRoot));
} else {
  outerQuery.multiselect(myResourceTableRoot.get("myId").as(Long.class));
  outerQuery.orderBy(orders);
  outerQuery.multiselect(myBuilder.countDistinct(myResourceTableRoot));
} else {
  outerQuery.multiselect(myResourceTableRoot.get("myId").as(Long.class));
} else {
  Predicate targetTypePredicate = myBuilder.equal(join.get("myTargetResourceType").as(String.class), myResourceName);
  Predicate sourceTypePredicate = myBuilder.equal(myResourceTableRoot.get("myResourceType").as(String.class), myResourceName);
  myPredicates.add(myBuilder.or(sourceTypePredicate, targetTypePredicate));

代码示例来源:origin: spring-projects/spring-data-jpa

query = query.multiselect(root.get((SingularAttribute) id).alias(id.getName()));
        .map(it -> (Selection<?>) root.get((SingularAttribute) it).alias(it.getName()))
        .collect(Collectors.toList()));
CriteriaQuery<? extends Object> select = query.orderBy(QueryUtils.toOrders(sort, root, builder));
return predicate == null ? select : select.where(predicate);

代码示例来源:origin: kiegroup/jbpm

/**
 * This is the main ("highest"? "most abstract"?) method that is used to create a {@link CriteriaQuery} from a {@link QueryWhere} instance.
 *
 * @param query The (empty) {@link CriteriaQuery} that will be filled using the {@link QueryCriteria} and other information in the {@link QueryWhere} instance
 * @param queryWhere The {@link QueryWhere} instance, with abstract information that should be added to the {@link CriteriaQuery}
 * @param builder The {@link CriteriaBuilder}, helpful when creating {@link Predicate}s to add to the {@link CriteriaQuery}
 * @param queryType The {@link Class} indicating the main {@link Root} of the {@link CriteriaQuery}
 */
protected <R,T> void fillCriteriaQuery( CriteriaQuery<R> query, QueryWhere queryWhere, CriteriaBuilder builder, Class<T> queryType ) {
  Predicate queryPredicate = createPredicateFromCriteriaList(query, builder, queryType, queryWhere.getCriteria(), queryWhere );
  if( queryPredicate != null ) {
    query.where(queryPredicate);
  }
  if( queryWhere.getAscOrDesc() != null ) {
    String orderByListId = queryWhere.getOrderByListId();
    assert orderByListId != null : "Ascending boolean is set but no order by list Id has been specified!";
    Expression orderByPath = getOrderByExpression(query, queryType, orderByListId);
    Order order;
    if( queryWhere.getAscOrDesc() ) {
      order = builder.asc(orderByPath);
    } else {
      order = builder.desc(orderByPath);
    }
    query.orderBy(order);
  }
}

代码示例来源:origin: DSpace/DSpace

@Override
  public VersionHistory findByItem(Context context, Item item) throws SQLException {
    CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context);
    CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, VersionHistory.class);
    Root<VersionHistory> versionHistoryRoot = criteriaQuery.from(VersionHistory.class);
    Join<VersionHistory, Version> join = versionHistoryRoot.join("versions");
    criteriaQuery.select(versionHistoryRoot);
    criteriaQuery.where(criteriaBuilder.equal(join.get(Version_.item), item));

    List<javax.persistence.criteria.Order> orderList = new LinkedList<>();
    orderList.add(criteriaBuilder.desc(join.get(Version_.versionNumber)));
    criteriaQuery.orderBy(orderList);

    return singleResult(context, criteriaQuery);
  }
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
public List<Order> readOrdersByDateRange(final Date startDate, final Date endDate) {
  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<Order> criteria = builder.createQuery(Order.class);
  Root<OrderImpl> order = criteria.from(OrderImpl.class);
  criteria.select(order);
  criteria.where(builder.between(order.<Date>get("submitDate"), startDate, endDate));
  criteria.orderBy(builder.desc(order.get("submitDate")));
  TypedQuery<Order> query = em.createQuery(criteria);
  query.setHint(QueryHints.HINT_CACHEABLE, true);
  query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
  return query.getResultList();
}

代码示例来源:origin: devicehive/devicehive-java-server

/**
 * Adds ORDER BY ... ASC/DESC to query
 * Mutates provided criteria query
 * @param sortFieldOpt - field to sort by (field name in JPA Entity class)
 * @param asc - true if order should be ASC, false otherwise
 */
public static void order(CriteriaBuilder cb, CriteriaQuery<?> cq, Root<?> from, Optional<String> sortFieldOpt, boolean asc) {
  sortFieldOpt.ifPresent(sortField -> {
    Order order = asc ? cb.asc(from.get(sortField)) : cb.desc(from.get(sortField));
    cq.orderBy(order);
  });
}

代码示例来源:origin: com.github.almex/raildelays-repository

private List<LineStop> findAll(Specifications<LineStop> specifications, Sort sort) {
  CriteriaBuilder builder = entityManager.getCriteriaBuilder();
  CriteriaQuery<LineStop> query = builder.createQuery(LineStop.class);
  Root<LineStop> root = query.from(LineStop.class);
  return entityManager
      .createQuery(query
          .where(specifications.toPredicate(root, query, builder))
          .orderBy(QueryUtils.toOrders(sort, root, builder)))
      .getResultList();
}

代码示例来源:origin: akquinet/jbosscc-as7-examples

@Override
public List<BlogEntry> find(int maxresults, int firstresult) {
  log.info("find blog entry, max results " + maxresults + " next result " + firstresult);
  CriteriaBuilder builder = getCriteriaBuilder();
  CriteriaQuery<BlogEntry> query = builder.createQuery(BlogEntry.class);
  Root<BlogEntry> from = query.from(BlogEntry.class);
  query.select(from).orderBy(builder.desc(from.get(BlogEntry_.created)));
  return getResultList(query, maxresults, firstresult);
}

代码示例来源:origin: spring-projects/spring-data-jpa

/**
 * Creates a new count query for the given {@link Specification}.
 *
 * @param spec can be {@literal null}.
 * @param domainClass must not be {@literal null}.
 * @return
 */
protected <S extends T> TypedQuery<Long> getCountQuery(@Nullable Specification<S> spec, Class<S> domainClass) {
  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<Long> query = builder.createQuery(Long.class);
  Root<S> root = applySpecificationToCriteria(spec, domainClass, query);
  if (query.isDistinct()) {
    query.select(builder.countDistinct(root));
  } else {
    query.select(builder.count(root));
  }
  // Remove all Orders the Specifications might have applied
  query.orderBy(Collections.<Order> emptyList());
  return em.createQuery(query);
}

代码示例来源:origin: org.jboss.pnc/spi

public static Predicate<BuildRecordPushResult> forBuildRecordOrderByIdDesc(Integer buildRecordId) {
  return (root, query, cb) -> {
    query.orderBy(cb.desc(root.get(BuildRecordPushResult_.id)));
    return cb.equal(root.get(BuildRecordPushResult_.buildRecord).get(BuildRecord_.id), buildRecordId);
  };
}

代码示例来源:origin: com.introproventures/graphql-jpa-query-schema

private void applyOrders(Root<T> from, CriteriaQuery<T> query) {
  List<Order> orderList = new ArrayList<>();
  for (Map.Entry<String, Boolean> me : orders.entrySet()) {
    Path<?> path = getCompoundJoinedPath(from, me.getKey(), true);
    if (me.getValue() == null || me.getValue().equals(true)) {
      orderList.add(criteriaBuilder.asc(path));
    } else {
      orderList.add(criteriaBuilder.desc(path));
    }
  }
  query.orderBy(orderList);
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

@Override
public List<Order> readOrdersForCustomersInDateRange(List<Long> customerIds, Date startDate, Date endDate) {
  CriteriaBuilder builder = em.getCriteriaBuilder();
  CriteriaQuery<Order> criteria = builder.createQuery(Order.class);
  Root<OrderImpl> order = criteria.from(OrderImpl.class);
  criteria.select(order);
  List<Predicate> restrictions = new ArrayList<>();
  restrictions.add(builder.between(order.<Date>get("submitDate"), startDate, endDate));
  restrictions.add(order.get("customer").get("id").in(customerIds));
  criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));
  criteria.orderBy(builder.desc(order.get("customer")), builder.asc(order.get("submitDate")));
  TypedQuery<Order> query = em.createQuery(criteria);
  query.setHint(QueryHints.HINT_CACHEABLE, true);
  query.setHint(QueryHints.HINT_CACHE_REGION, "query.Order");
  return query.getResultList();
}

代码示例来源:origin: adorsys/xs2a

private Specification<EventEntity> eventPeriodSpecification(OffsetDateTime start, OffsetDateTime end) {
    return (root, criteriaQuery, criteriaBuilder) -> {
      criteriaQuery.orderBy(criteriaBuilder.asc(root.get(TIMESTAMP_ID_ATTRIBUTE)));
      return criteriaBuilder.between(root.get(TIMESTAMP_ID_ATTRIBUTE), start, end);
    };
  }
}

代码示例来源:origin: madvirus/ddd-start

@Override
public List<Order> findAll(Specification<Order> spec, String ... orders) {
  CriteriaBuilder cb = entityManager.getCriteriaBuilder();
  CriteriaQuery<Order> criteriaQuery = cb.createQuery(Order.class);
  Root<Order> root = criteriaQuery.from(Order.class);
  Predicate predicate = spec.toPredicate(root, cb);
  criteriaQuery.where(predicate);
  if (orders.length > 0) {
    criteriaQuery.orderBy(JpaQueryUtils.toJpaOrders(root, cb, orders));
  }
  TypedQuery<Order> query = entityManager.createQuery(criteriaQuery);
  return query.getResultList();
}

相关文章