org.springframework.data.domain.Sort#Order ( )源码实例Demo

下面列出了org.springframework.data.domain.Sort#Order ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: spring-data   文件: ArangoRepositoryTest.java
@Test
public void findAllSortByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "C", 0));
	toBeRetrieved.add(new Customer("B", "D", 0));
	repository.saveAll(toBeRetrieved);
	repository.save(new Customer("A", "A", 1));
	final Example<Customer> example = Example.of(new Customer("", "", 0),
		ExampleMatcher.matchingAny().withIgnoreNullValues().withIgnorePaths(new String[] { "location", "alive" }));
	final List<Sort.Order> orders = new LinkedList<>();
	orders.add(new Sort.Order(Sort.Direction.ASC, "name"));
	orders.add(new Sort.Order(Sort.Direction.ASC, "surname"));
	final Sort sort = Sort.by(orders);
	final Iterable<Customer> retrieved = repository.findAll(example, sort);
	assertTrue(equals(toBeRetrieved, retrieved, cmp, eq, true));
}
 
public PageRequest getPageRequestForNotifications(Integer pageNumber, Integer pageSize, String sortField, String sortOrder) {
    Integer page = ObjectUtils.defaultIfNull(pageNumber, 0);
    Integer size = ObjectUtils.defaultIfNull(pageSize, Integer.MAX_VALUE);
    boolean sortQuery = false;
    String sortingField = "createdAt";
    // We can only modify the query for the fields that exist in NotificationContent
    if (StringUtils.isNotBlank(sortField) && "createdAt".equalsIgnoreCase(sortField)
            || "provider".equalsIgnoreCase(sortField)
            || "providerCreationTime".equalsIgnoreCase(sortField)
            || "notificationType".equalsIgnoreCase(sortField)
            || "content".equalsIgnoreCase(sortField)) {
        sortingField = sortField;
        sortQuery = true;
    }
    Sort.Order sortingOrder = Sort.Order.desc(sortingField);
    if (StringUtils.isNotBlank(sortOrder) && sortQuery && Sort.Direction.ASC.name().equalsIgnoreCase(sortOrder)) {
        sortingOrder = Sort.Order.asc(sortingField);
    }
    return PageRequest.of(page, size, Sort.by(sortingOrder));
}
 
源代码3 项目: fw-cloud-framework   文件: DictServiceImpl.java
@Override
@Cacheable(key = "'page_dict_' + #p0.currentPage + '_' + #p0.pageSize + '_' + #p1.type + '_' + #p1.label")
public PageBean<Dict> findAll(PageParams pageParams, Dict dict) {
	QDict qDict = QDict.dict;
	// 用户名查询条件
	Predicate qLabelPredicate = null;
	Predicate qTypePredicate = null;
	if (null != dict) {
		if (StringHelper.isNotBlank(dict.getLabel())) {
			qLabelPredicate = qDict.label.like("%" + dict.getLabel().trim() + "%");
		}
		if (StringHelper.isNotBlank(dict.getType())) {
			qTypePredicate = qDict.type.like("%" + dict.getType().trim() + "%");
		}
	}

	Predicate predicate = qDict.id.goe(0).and(qTypePredicate).and(qLabelPredicate);

	Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "id"));
	PageRequest pageRequest = PageUtils.of(pageParams, sort);
	Page<Dict> pageList = dictRepository.findAll(predicate, pageRequest);
	return PageUtils.of(pageList);
}
 
@Override
public Sort deserialize(JsonParser jsonParser,
		DeserializationContext deserializationContext) throws IOException {
	TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
	if (treeNode.isArray()) {
		ArrayNode arrayNode = (ArrayNode) treeNode;
		List<Sort.Order> orders = new ArrayList<>();
		for (JsonNode jsonNode : arrayNode) {
			Sort.Order order = new Sort.Order(
					Sort.Direction.valueOf(jsonNode.get("direction").textValue()),
					jsonNode.get("property").textValue());
			orders.add(order);
		}
		return Sort.by(orders);
	}
	return null;
}
 
@Transactional(rollbackFor = Exception.class)
@Override
public void reSendAllDeadByQueueName(String queueName, int batchSize)
        throws CheckException, ServiceException {

    int pageNum = 0;
    int totalPage = 1;
    while (pageNum++ < totalPage) {
        Sort.Order order = new Sort.Order("createTime");
        Sort sort = new Sort(order);
        Pageable pageable = new PageRequest(pageNum, batchSize, sort);
        Page<Message> page = messageRepository.findByConsumerQueueAndDead(queueName, Boolean.TRUE, pageable);

        totalPage = page.getTotalPages();
        reSendNoDead(page.getContent());
    }
}
 
源代码6 项目: code-examples   文件: PageableAssert.java
PageableAssert hasSort(String field, Sort.Direction direction) {

		Sort.Order actualOrder = actual.getSort().getOrderFor(field);

		if (actualOrder == null) {
			failWithMessage("expected sort for field <%s> to be <%s> but was null", field, direction);
		} else if (actualOrder.getDirection() != direction) {
			failWithMessage("expected sort for field <%s> to be <%s> but was <%s>", field, direction, actualOrder.getDirection());
		}

		return this;
	}
 
源代码7 项目: spring-boot   文件: JpaUtils.java
/**
 * 根据 jqgrid 传过来的排序信息,构造排序所需要的 Sort
 *
 * @param order
 * @return
 */
private static Sort getJqGirdSort(Order order) {

    if (order.getProperty() == null || order.getProperty().isEmpty()) {
        log.info("排序字段为 null 或 空");
        return null;
    }

    //排序字段
    if (!order.getProperty().contains(",")) { //未分组

        return createSort(order.getDirection().toString(), order.getProperty());

    } else { //分组,grouping:true 时

        String[] arrays = StringUtils.removeEnd(order.getProperty().trim(), ",").split(",");  //传来的排序请求字符串,形如 sidx =name asc, herf desc,实际经过参数对应后变成字符串 name asc, herf desc,
        //arrays = {[name asc],[herf desc]}

        List<Sort.Order> orders = Lists.newArrayList();
        List<String> unique = Lists.newArrayList();   //为了避免同一个属性,重复添加。此情况发生在 grouping:true 时,没有进一步测试。
        for (String s : arrays) { //拼接所有的排序请求。
            String propertyT = StringUtils.substringBefore(s.trim(), " ");
            if (unique.contains(propertyT))
                continue;
            unique.add(propertyT);
            String directionT = StringUtils.substringAfter(s.trim(), " ");
            orders.add(createOrder(directionT, propertyT));
        }
        return createSort(orders);
    }
}
 
源代码8 项目: ZTuoExchange_framework   文件: Criteria.java
/**
 * 排序
 * QueryBuilderUtils.sort("name","id.desc");表示先以name升序,之后以xh降序
 */
public  Sort sort(String... fields) {
    List<Sort.Order> orders = new ArrayList<Sort.Order>();
    for(String f:fields) {
        orders.add(generateOrderStatic(f));
    }
    return new Sort(orders);
}
 
@Override
public BindingResult<Pageable> bind(ArgumentConversionContext<Pageable> context, HttpRequest<?> source) {
    HttpParameters parameters = source.getParameters();
    int page = Math.max(parameters.getFirst(configuration.getPageParameterName(), Integer.class)
            .orElse(0), 0);
    final int configuredMaxSize = configuration.getMaxPageSize();
    final int defaultSize = configuration.getDefaultPageSize();
    int size = Math.min(parameters.getFirst(configuration.getSizeParameterName(), Integer.class)
            .orElse(defaultSize), configuredMaxSize);
    String sortParameterName = configuration.getSortParameterName();
    boolean hasSort = parameters.contains(sortParameterName);
    Pageable pageable;
    Sort sort;
    if (hasSort) {
        List<String> sortParams = parameters.getAll(sortParameterName);

        List<Sort.Order> orders = sortParams.stream()
                .map(sortMapper)
                .collect(Collectors.toList());
        sort = Sort.by(orders);
    } else {
        sort = Sort.unsorted();
    }

    if (size < 1) {
        if (page == 0 && configuredMaxSize < 1 && sort.isUnsorted()) {
            pageable = Pageable.unpaged();
        } else {
            pageable = PageRequest.of(page, defaultSize, sort);
        }
    } else {
        pageable = PageRequest.of(page, size, sort);
    }

    return () -> Optional.of(pageable);
}
 
/**
 * Api 查询订单接口
 *
 * @param memberId
 * @param symbol
 * @param direction
 * @return
 */
public Page<ExchangeOrder> findCurrentTradingOrderForApi(long memberId, String symbol, ExchangeOrderDirection direction, int pageNo, int pageSize) {
    Sort orders = new Sort(new Sort.Order(Sort.Direction.DESC, "time"));
    PageRequest pageRequest = new PageRequest(pageNo, pageSize, orders);
    Criteria<ExchangeOrder> specification = new Criteria<ExchangeOrder>();
    specification.add(Restrictions.eq("symbol", symbol, false));
    specification.add(Restrictions.eq("memberId", memberId, false));
    specification.add(Restrictions.eq("status", ExchangeOrderStatus.TRADING, false));
    specification.add(Restrictions.eq("direction", direction, false));
    return exchangeOrderRepository.findAll(specification, pageRequest);
}
 
public List<ExchangeCoin> findAllEnabled() {
    Specification<ExchangeCoin> spec = (root, criteriaQuery, criteriaBuilder) -> {
        Path<String> enable = root.get("enable");
        criteriaQuery.where(criteriaBuilder.equal(enable, 1));
        return null;
    };
    Sort.Order order = new Sort.Order(Sort.Direction.ASC, "sort");
    Sort sort = new Sort(order);
    return coinRepository.findAll(spec, sort);
}
 
源代码12 项目: ZTuoExchange_framework   文件: MarketService.java
public List<KLine> findAllKLine(String symbol,long fromTime,long toTime,String period){
    Criteria criteria = Criteria.where("time").gte(fromTime).andOperator(Criteria.where("time").lte(toTime));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    List<KLine> kLines = mongoTemplate.find(query,KLine.class,"exchange_kline_"+symbol+"_"+ period);
    return kLines;
}
 
源代码13 项目: ZTuoExchange_framework   文件: MarketService.java
/**
 * 查找某时间段内的交易量
 * @param symbol
 * @param timeStart
 * @param timeEnd
 * @return
 */
public BigDecimal findTradeVolume(String symbol, long timeStart, long timeEnd){
    Criteria criteria = Criteria.where("time").gt(timeStart)
            .andOperator(Criteria.where("time").lte(timeEnd));
            //.andOperator(Criteria.where("volume").gt(0));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    List<KLine> kLines =  mongoTemplate.find(query,KLine.class,"exchange_kline_"+symbol+"_1min");
    BigDecimal totalVolume = BigDecimal.ZERO;
    for(KLine kLine:kLines){
        totalVolume = totalVolume.add(kLine.getVolume());
    }
    return totalVolume;
}
 
@Override
public Sort sort(BaseServiceLogRequest request) {
  String sortBy = request.getSortBy();
  String sortType = request.getSortType();
  Sort.Order defaultSortOrder;
  if (StringUtils.isNotBlank(sortBy)) {
    Sort.Direction direction = StringUtils.equals(sortType, LogSearchConstants.ASCENDING_ORDER) ? Sort.Direction.ASC : Sort.Direction.DESC;
    defaultSortOrder = new Sort.Order(direction, sortBy);
  } else {
    defaultSortOrder = new Sort.Order(Sort.Direction.DESC, LOGTIME);
  }
  Sort.Order sequenceIdOrder = new Sort.Order(Sort.Direction.DESC, SEQUENCE_ID);
  return new Sort(defaultSortOrder, sequenceIdOrder);
}
 
源代码15 项目: SuperBoot   文件: LogServiceImpl.java
@Override
public BaseResponse getRequestCountByWeek() throws BaseException {

    //查询条件信息
    Criteria operator = new Criteria();
    operator.andOperator(
            //查询小于等于今天
            Criteria.where("execDate").lte(DateUtil.today()),
            //查询大于等于7天前
            Criteria.where("execDate").gte(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -7)))

    );

    //查询条件
    MatchOperation matchOperation = Aggregation.match(operator);


    //分组信息及返回count列命名
    GroupOperation groupOperation = Aggregation.group("appName", "execDate").count().as("count");

    //排序信息
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "execDate"));
    SortOperation sortOperation = Aggregation.sort(sort);

    //组合条件
    Aggregation aggregation = Aggregation.newAggregation(DataInfo.class, matchOperation, groupOperation, sortOperation);

    // 执行操作
    AggregationResults<Map> aggregationResults = template.aggregate(aggregation, DataInfo.class, Map.class);

    return new BaseResponse(aggregationResults.getMappedResults());
}
 
源代码16 项目: ZTuoExchange_framework   文件: Criteria.java
/**
 * 排序
 * QueryBuilderUtils.sort("name","id.desc");表示先以name升序,之后以xh降序
 */
public  Sort sort(String... fields) {
    List<Sort.Order> orders = new ArrayList<Sort.Order>();
    for(String f:fields) {
        orders.add(generateOrderStatic(f));
    }
    return new Sort(orders);
}
 
源代码17 项目: platform   文件: PaginationInterceptor.java
private static List<OrderByElement> addOrderByElements(List<Sort.Order> orderList,
                                                       List<OrderByElement> orderByElements) {
    orderByElements = CollectionUtils.isEmpty(orderByElements) ? new ArrayList<>(orderList.size()) : orderByElements;
    List<OrderByElement> orderByElementList = orderList.stream().map(item -> {
        OrderByElement element = new OrderByElement();
        element.setExpression(new Column(item.getProperty()));
        element.setAsc(item.getDirection().isAscending());
        return element;
    }).collect(Collectors.toList());
    orderByElements.addAll(orderByElementList);
    return orderByElements;
}
 
源代码18 项目: springlets   文件: QueryDslRepositorySupportExt.java
/**
 * Applies the given {@link Pageable} to the given {@link JPQLQuery}.
 * Allows to map the attributes to order as provided in the {@link Pageable}
 * to real entity attributes. This might be used to work with projections
 * or DTOs whose attributes don't have the same name as the entity ones.
 *
 * It allows to map to more than one entity attribute. As an example, if
 * the DTO used to create the {@link Pageable} has a fullName attribute, you
 * could map that attribute to two entity attributes: name and surname.
 * In this case, the {@link Pageable} defines an order by a fullName
 * attribute, but que query will order by name and surname instead.
 *
 * @param pageable the ordering and paging
 * @param query
 * @param attributeMapping definition of a mapping of order attribute names
 *        to real entity ones
 * @return the updated query
 */
protected JPQLQuery<T> applyPagination(Pageable pageable, JPQLQuery<T> query,
    Map<String, Path<?>[]> attributeMapping) {

  if (pageable == null) {
    return query;
  }

  Pageable mappedPageable;
  Sort sort = pageable.getSort();
  if (sort != null) {
    List<Sort.Order> mappedOrders = new ArrayList<Sort.Order>();
    for (Sort.Order order : sort) {
      if (!attributeMapping.containsKey(order.getProperty())) {
        LOG.warn(
            "The property (%1) is not included in the attributeMapping, will order "
                + "using the property as it is",
            order.getProperty());
        mappedOrders.add(order);
      } else {
        Path<?>[] paths = attributeMapping.get(order.getProperty());
        for (Path<?> path : paths) {
          Sort.Order mappedOrder =
              new Sort.Order(order.getDirection(), preparePropertyPath(path));
          mappedOrders.add(mappedOrder);
        }
      }
    }
    if (mappedOrders.isEmpty()) {
      // No properties to order by are available, so don't apply ordering and return the query
      // as it is
      return query;
    }
    mappedPageable =
        new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(mappedOrders));
    return applyPagination(mappedPageable, query);
  } else {
    return applyPagination(pageable, query);
  }

}
 
源代码19 项目: ZTuoExchange_framework   文件: MarketService.java
public ExchangeTrade findFirstTrade(String symbol,long fromTime,long toTime){
    Criteria criteria = Criteria.where("time").gte(fromTime).andOperator(Criteria.where("time").lte(toTime));
    Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"time"));
    Query query = new Query(criteria).with(sort);
    return mongoTemplate.findOne(query,ExchangeTrade.class,"exchange_trade_"+symbol);
}
 
源代码20 项目: spring-boot   文件: JpaUtils.java
/**
 * 创建排序条件 Order
 *
 * @param direction
 * @param property
 * @return
 */
public static Sort.Order createOrder(String direction, String property) {
    Assert.isTrue(!property.isEmpty(), " 排序字段没有指定");
    return new Sort.Order(createDirection(direction), property);
}